I'm struggling with maxJsonLength error.
I'm passing very long xml string (~4MB) from controller action to javascript method in a View. This method proceses data and send it back with AJAX to another controller method, and here I'm getting error.
I've set MaxJsonLength in JsonResult object, in the controller method, and the is no problem with passing this string from controller to view.
But when I'm try to pass it back after processing I'm getting error.
This is my Controller method whitch prepare data:
private JsonResult PrepareXml(int someId)
{
// preparing data...
string xmlData = "..."; //(~4Mb)
JsonResult res = Json(xmlData);
res.MaxJsonLength = 10000000; // 10Mb
return res;
}
And this is my Controller method whitch is trying to proces data passed from ajax method:
private JsonResult GetProcesedXml(string resultXml)
{
// This method is not ivoking
}
And below is my script method:
var data = {
someId: rowId,
};
$.ajax({
type: "POST",
url: "MyController/PrepareXml",
data: data,
contentType: "application/json; charset=utf-8",
success: function (result) {
// proces the result (big xml file)
//...
var processedResult = ""; // size of processedResult is a little bit bigger than 'result'
var data2 = {
resultXml: processedResult
};
$.ajax({
type: "POST",
url: "MyController/GetProcesedXml",
data: data2,
contentType: "application/json; charset=utf-8",
success: function (r) {
alert('success');
},
error: function (data) {
alert(data.responseText);
}
});
}
});
What I've tried already:
<add key="aspnet:MaxJsonDeserializerMembers" value="2147483647" /> //(max value)
<requestLimits maxAllowedContentLength="2097151000" /> //(max value)
<httpRuntime maxRequestLength="10000" /> //(~10MB)
I've found some workaround for this problem.
I've changed content type in Ajax method to "text/plain" and used JSON.stringify on my xml file data.
var data2 = { resultXml: processedResult };
$.ajax({
type: "POST",
url: "MyController/GetProcesedXml",
data: JSON.stringify(data2),
contentType: "text/plain",
success: function (r) {
alert('success');
},
});
Another change is in controller. I've read file from input stream and parse it to form JSON type:
private JsonResult GetProcesedXml()
{
JObject json = null;
Stream request = Request.InputStream;
using (StreamReader sr = new StreamReader(stream))
{
stream.Seek(0, System.IO.SeekOrigin.Begin);
json = JObject.Parse(sr.ReadToEnd());
}
string xmlSigninigResult = json["resultXml"].ToString();
// rest of the method
}
Related
I want to pass the variable from view to controller I am using ajax call to achieve it i am getting the error below. I don't know what i am missing here.
WARN 41440 --- [nio-8080-exec-9] o.s.web.servlet.PageNotFound : Request method 'POST' not supported
This is my code
document.getElementById('btntest').onclick = function(){
var selchbox = getSelectedChbox(this.form); // gets the array returned by getSelectedChbox()
myvalue = JSON.stringify(selchbox);
//document.write("check check"+selchbox);
$.ajax({
type: "POST",
url: "UserController/delete",
contentType: "application/json; charset=utf-8",
data: {key:myvalue},
cache: false,
success: function (data) {
alert("Are you sure?");
},
error: function (args) {
alert("Error on ajax post");
}
});
alert(selchbox);
}
My controller method looks like below
#RequestMapping(value = "/delete", method = RequestMethod.POST)
public String delete(#RequestBody String key) {
System.out.println("My Array value"+key.toString());
return key;
}
What i am missing here? Any Help
Finally i could able to pass the values from my view to controller I am posting the code.
This is my js code
document.getElementById('btntest').onclick = function(){
var selchbox = getSelectedChbox(this.form); // gets the array returned by getSelectedChbox()
var myvalue = JSON.stringify(selchbox);
//document.write("check check"+selchbox);
$.ajax({
type: "POST",
url: "/delete",
dataType : "JSON",
contentType:"application/json; charset=utf-8",
data: JSON.stringify(selchbox),
cache: false,
success: function (data) {
alert("Are you sure?");
},
error: function (args) {
alert("Error on ajax post");
}
});
alert(selchbox);
}
And my controller code
#RequestMapping(value = "/delete", method = RequestMethod.POST)
public String delete(#RequestBody String value){
System.out.println("My Array value"+value.toString());
return value;
}
First, if you want to delete, why not use the verb delete http?
I think you are not using the correct parameter: RequestParam is used to map your sORGID parameter to the URL (a parameter you did not use on the client side, you must use it or delete it).
If you want to map Json, you must use #RequestBody.
I hope it helps
At leaset two problems
url: "UserController/delete" in your ajax won't match "/delete/{sORGID}" in your controller.
data: {key:myvalue} in your ajax, the property name is key, in your controller it's myvalue[], this should also be the same.
This is my api code that return successfull json data while using get method
public Question[] Get() {
getQuestion obj = new AllDataAccess.getQuestion();
return obj.questionList().ToArray();
}
This is my post method data that accept the value and save in database
public void Post([FromBody] string question) {
SaveQuestion obj = new AllDataAccess.controller.SaveQuestion();
obj.savaData(question);
}
This is the method that call my api
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'http://localhost:53893/api/values',
data: "{'question':'" + $("#submit").value + "'}",
dataType: 'json',
async: false,
success: function(data, status) {
console.log(status);
},
error: function(err) {
console.log(err);
}
});
Now the problem is when i post the data with one textbox value its give me a message in console that "nocontent" and record save in data base with null value
It seems that your ajax url is wrong. You should specify the action name (post). Also, use JSON.stringify to retrieve proper json from javascript object.
var postData = { question:$("#submit").val() };
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'http://localhost:53893/api/values/post',
data: JSON.stringify(postData),
dataType: 'json',
success: function (data,status) {
console.log(status);
},
error: function (err) {
console.log(err);
}
});
In the server side, you should create a model class for Post method;
public class PostInput
{
public string Question { get; set; }
}
And then Post method looks like;
[HttpPost]
public void Post([FromBody]PostInput input)
{
SaveQuestion obj = new AllDataAccess.controller.SaveQuestion();
obj.savaData(question);
}
If you want to use FromBody, you can do so.
JavaScript
$.ajax({
type: "POST",
//default content-type, could be omitted
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
url: 'http://localhost:53893/api/values/post',
data: {'': $("#submit").val()}
});
API action
[HttpPost]
public void Post([FromBody]string question)
{
SaveQuestion obj = new AllDataAccess.controller.SaveQuestion();
obj.savaData(question);
}
You had these issues.
Wrong content-type for your ajax call.
Data was not posted correctly.
val() should be used instead of .value.
API action should be decorated with [HttpPost].
i am writing a function in jquery which post the data to controller. currently it is posting form data to controller fine but when i post checkbox list with form data then it send always count 0 in controller here is my code.
function SubmitForm() {
var studentFormData = $("#frmStudent").serialize();
debugger;
var SubjectArraydata = new Array();
$(".chkSubject:checked").each(function () {
var row = {
"SubjectId": $(this).data("id")
};
SubjectArraydata.push(row);
});
$.ajax({
url: '#Url.Action("StudentForm", "Student")',
type: "POST",
dataType: "json",
data: studentFormData + JSON.stringify("&subjectData=" + SubjectArraydata),
async: true,
success: function (msg) {
},
error: function () {
}
});
}
Controller:
[HttpPost]
public ActionResult StudentForm(Student student, List<Subject> subjectData)
{
return Json(true);
}
any one tell me where is the problem in my code thank you.
Your cannot mix 'application/x-www-form-urlencoded' data (the contentType of your serialize() method) and 'application/json' data (the contentType of the JSON.stringify() method) like that.
Sinve you have confirmed that your only submitting one property of Subject, which is SubjectId and is typeof int, then you can append the SubjectId values to the serialized data.
var studentFormData = $("#frmStudent").serialize();
$(".chkSubject:checked").each(function () {
studentFormData += '&' + $.param({ SubjectIds: $(this).data("id") });
};
$.ajax({
url: '#Url.Action("StudentForm", "Student")',
type: "POST",
dataType: "json",
data: studentFormData,
success: function (msg) {
},
error: function () {
}
});
and change your controller method to
[HttpPost]
public ActionResult StudentForm(Student student, List<int> SubjectIds)
{
....
I think you use 'POST' method not correctly. You try to mix sending data as json and as url parameters.
data: studentFormData + JSON.stringify("&subjectData=" + SubjectArraydata),
what you send in data:
[
{...},
[{SubjectId: ''}, {SubjectId: ''}]
]
or:
{
1: {...},
subjectData: [{SubjectId: ''}, {SubjectId: ''}]
}
or some data sended as json, some in url?
Send all data in json, and dont serialize (jquery do it for you):
var data = [strudentFormData, subjectData];
$.ajax(..., data: data, ...);
I use Asp.Net WebApi and jQuery.
From page to WebApi i send 'POST' HTTP-Request with object.
$.ajax({
type: "POST",
url: "api/Result",
data: JSON.stringify(makeResultInfo()),//makeResultInfo - function that returns object
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: true,
success: function (data) {
window.location = data;
alert("success");
},
error: function (xhr) {
alert('error');
}
});
WebApi take object correctly and return Excel-file.
[HttpPost]
public HttpResponseMessage Post([FromBody]ResultInfo value)
{
ExcelClass ec = new ExcelClass();
var stream = ec.GetStream(ec.mini_wb);//после теста поправить
// processing the stream.
var result = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(stream.ToArray())
};
result.Content.Headers.ContentDisposition =
new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
{
FileName = "test.xlsx"
};
result.Content.Headers.ContentType =
new MediaTypeHeaderValue("application/octet-stream");
return result;
}
When i make Request to 'api/Result' without parameters - file downloading correctly. But when i send object, response incorrect always and alert always write 'error'.
How i can send object and take file in browser?
I try to send values from my view to my controller.
The method in my controller is called but the value(s) still remain NULL.
Here is the Javascript part:
GUIRequests.prototype.SetNewItemDeliveryValues = function () {
var modelNumberID = this.GetValue('#ModelNumberID');
this.Request.GetPreOrderIDForModelNumberID(modelNumberID); //InventValueRequest
this.Request.GetShortfallAndOverdeliveryInNewItemDelivery(modelNumberID);
}
InventValueRequest.prototype.GetPreOrderIDForModelNumberID = function (_modelNumberID) {
this.CallAjax("/NewItemDelivery/GetPreOrderIDForModelNumberID", _modelNumberID, CallbackMethods.SetPreOrderID);
}
//Private
InventValueRequest.prototype.CallAjax = function (_url, _data, _successFunctionPointer) {
$.ajax({
type: 'POST',
url: _url,
contentType: 'application/json',
data: JSON.stringify(_data),
success: _successFunctionPointer,
error: InventValueRequest.HandleError
});
}
Asp.Net MVC5 (C#) part
[HttpPost]
public ActionResult GetPreOrderIDForModelNumberID(string _modelnumberID)
{
String preOrderID = "";
if (_modelnumberID == null)
{
preOrderID = "No value received";
}
else
{
//Do something
}
return Json(preOrderID);
}
What could be the problem with my code ? why don't I receive any values in my C# part ? It seems that the values get send correctly, at least the payload contains the values I would expect.
_data should have the property _modelnumberID like following.
_data = {'_modelnumberID': '1'}
try below code :
$.ajax({
type: 'POST',
dataType: 'text',
url: _url,
contentType: 'application/json',
data: "_modelnumberID=" + _data,
success: _successFunctionPointer,
error: InventValueRequest.HandleError
});
The Ideal solution would be to use a view model.
public class Create
{
public string _modelnumberID{get;set;}
}
And your HttpPost action would be accepting an object of this
[HttpPost]
public ActionResult View(Create model)
{
// do something and return something
}
and ajax will be
$('.submit').click(function () {
var myData = {
_modelnumberID: _data
}
$.ajax({
url: '/Controller/Action',
type: 'POST',
data: myData,
processData: false
}).done(function () {
}).fail(function () {
});
});
$.ajax({
type: 'POST',
url: _url+"?_modelnumberID="+ _data,
success: _successFunctionPointer,
error: InventValueRequest.HandleError
});
Try this.