I'm Trying to send large Data amount using ajax , it returns 404 error Not found , and if I send small amount of Data it respond with 200 and work Normally
here is my Code
var str = myDiagram.model.toJson();
document.getElementById("mySavedModel").value = str;
myDiagram.isModified = false;
$.ajax({
dataType: "json",
url: "/Workflow/PraseJson/?diagram=" + str
}).done(function (x) {
});
and Code for Controller
public void PraseJson(string diagram)
{
object yourOjbect = new JavaScriptSerializer().DeserializeObject(diagram);
}
I do not know how to solve this Issue, Can anyone help ?
Try using POST to send data
$.ajax({
dataType: "json",
type: "POST",
data: {diagram: str },
url: "/Workflow/PraseJson/
}).done(function (x) { });
[HttpPost]
public void PraseJson(string diagram)
{
object yourOjbect = new JavaScriptSerializer().DeserializeObject(diagram);
}
Related
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
}
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 know it seems to be better to use normal call instead of AJAX call but for some reason i.e. displaying error message on modal dialog in case a problem during download, I need to download file by using an AJAX call in an MVC5 project. Here is what I did finally after lot of tries:
View:
Download
function downloadFile() {
$.ajax({
type: 'POST',
url: '/Experiment/GetFile',
data: '{id:' + 8 + '}', //For test purpose I used static id
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (returnValue) {
window.location = '/Experiment/GetFile?id=' + returnValue;
}
});
};
Controller:
In Controller, I have a method something like that, but I am really confused if I should do the same method for AJAX Post and success method or not.
[HttpPost]
public ActionResult GetFile(int id)
{
var dataContext = repository.FileAttachments.FirstOrDefault(m => m.Id == id);
if (dataContext == null)
{
return Json(new { success = true, returnValue = "8" });
}
else
{
return Json(new { success = false, message= "Error..." }, JsonRequestBehavior.AllowGet);
}
}
Is there a smart approach to perform this dosnload operation using AJAX call in ASP.NET MVC5?
You need to return file name or file path
Example "/file/download.doc"
And then you need to edit view page like follow
Download
<a href="" id="todownload" download>
function downloadFile() {
$.ajax({ type: 'POST', url: '/Experiment/GetFile', data: '{id:' + 8 + '}', //For test purpose I used static id
contentType: 'application/json; charset=utf-8', dataType: 'json',
success: function (returnValue)
$("#todownload").attr('href',returnValue);
$("#todownload").click();
}
});
};
I keep getting a 405 error upon a POST method
$.ajax({
url: mistergoUrl,
type: "POST",
dataType: "json",
data: body,
crossDomain: true,
contentType: "application/json",
success: function () {
// TODO: find a cleaner way to get the last route
$.getJSON(mistergoUrl)
.done(function (data) {
data = resolveReferences(data);
window.location.replace("Route.html?id=" + data.last().RouteId);
});
},
error: function (httpObj, result) {
Console.log(result);
Console.log(httpObj);
}
});
On the server, the request is valid, is processed and returned as expected, but the Ajax function keeps giving back a 405 error...
This is the asp.net code
[HttpPost]
public IHttpActionResult Post(RoutePostModel postdata)
{
if (!ModelState.IsValid)
{
return BadRequest();
}
_routeService.Add(postdata);
var route = _routeService.GetAll().Last();
var url = Url.Route("DefaultApi", new {controller = "Routes", id = route.RouteId});
return Created(url, route);
}
Does anybody know why and how this could happen? any help is appreciated!
I am trying to sent a byte[] in a postback action, but failed to get it.
Code snippets:
$.ajax({
url: proxy.Model.RequestParamUrl,
type: "Post",
async: false,
data: proxy.requestArgs,
dataType: 'json',
success: function (Jsondata) {
proxy.allowPost = false;
proxy.postSucceed = true;
//hidden code
return true;
}
});
While debugging, I can see byte[] in proxy.requestArgs.
But in the controller, I get null in this action result.
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(byte[] param)
{
//I get null in this param.
}
Anything I am missing out?
Any Solution
You're passing data to the controller action and that action is expecting a post item named param. So in your JS, make your ajax call look like this (note the change to data):
$.ajax({
url: proxy.Model.RequestParamUrl,
type: "Post",
async: false,
data: { param: proxy.requestArgs },
dataType: 'json',
success: function (Jsondata) {
proxy.allowPost = false;
proxy.postSucceed = true;
//hidden code
return true;
}
});
Have you tried this?
Basically, accept the data as string in you action and inside it convert it into byte[]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(string param)
{
var bytes = System.Text.Encoding.UTF8.GetBytes(param);
}