MVC Send list through AJAX - c#

Okay, I've seen tons of questions posted regarding this question, but none of the answers has actually worked for me, here's my AJAX:
$.ajax({
url: "/FilterSessions/GetFilterSession",
type: "GET",
dataType: "json",
data: jsonFilters,
traditional: true,
success: function (response) {
//Haha, it's never entering here. not really.
}
});
var "jsonFilters" contains an array with the following data:
[0] = { Path: "Test", Name: "More testing", Value: "Test Value" },
[1] = { Path: "Test", Name: "More testing", Value: "Test Value" }
And this is my controller:
public ActionResult GetFilterSession(List<FilterSessionModel> jsonFilters)
{
//Do things
return Json(false, JsonRequestBehavior.AllowGet);
}
jsonFilters always remains null... I have also tried adding contentType: "application/json; charset=utf-8" to the AJAX call... but that didn't really do anything
Finally, the class FilterSessionModel is structured as follows:
public class FilterSessionModel
{
public string Path { get; set; }
public string Name { get; set; }
public string Value { get; set; }
}
Any ideas as to what I might be missing or what might be happening?
Things I've tried so far:
Setting "traditional: true", setting "contentType", using JSON.stringify and attempting to accept a string in the MVC Controller (no-go)
UPDATE: Thanks to the answer below I realized that what was missing was to send over the data with the param Id like so:
data: "{param1ID:"+ param1Val+"}"

I would try switching out the type on your action.
List<FilterSessionModel>
Pretty sure the above is not going to work, I would try something like Object.
Or possibly a string that I would then use newton json dll to push into your List of Class.
The problem boils down to your action being unable to figure out the type, assuming you are checking your data prior to the ajax get being called.
**Update due to more info. Add in the error portion and view those vars on return from your controller, also fire up fiddler and watch what your are getting for http numbers.
$.ajax({
type: "POST",
url: "Servicename.asmx/DoSomeCalculation",
data: "{param1ID:"+ param1Val+"}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
UseReturnedData(msg.d);
},
error: function(x, t, m, b) {
//Look at the vars above to see what is in them.
}
});

I think what you are looking for is answered here:
Passing A List Of Objects Into An MVC Controller Method Using jQuery Ajax

First off I'm making the assumption that your $.ajax is for JQuery and not some other Javascript framework. Please correct me if that's wrong.
ASP.NET MVC can actually do what you are asking it to (resolve data sent via AJAX to a List<FilterSessionModel>, but it seems to have a difficult time doing it via a GET request. It would help to know which version of ASP.NET MVC you are using, as more is required to get this working on the older versions. However, what I'm suggesting should work on MVC 3 or 4.
When you send AJAX via JQuery using a GET request and passing it a JavaScript array, this is what you are sending to the server:
http://localhost:50195/FilterSessions/GetFilterSession?undefined=&undefined=
It's no wonder the model is null because no data is actually being sent.
I believe ASP.NET can accept objects (and even arrays of objects) like this, but it won't do so with it formatted as JSON (like via JSON.stringify) as that just results in the following request:
http://localhost:50195/FilterSessions/GetFilterSession?[{%22Path%22:%22Test%22,%22Name%22:%22TestName%22,%22Value%22:%22Testing%22},{%22Path%22:%22Test%22,%22Name%22:%22TestName%22,%22Value%22:%22Testing%22}]
The way you probably want to do this is with a POST request. ASP.NET MVC will actually accept a JSON string as POST data and will decode it and resolve the model properly. Your AJAX code works fine with a couple modifications:
$.ajax({
url: "/FilterSessions/GetFilterSession",
type: "POST", //Changed to POST
dataType: "json",
data: JSON.stringify(jsonFilters), //Pack data in a JSON package.
contentType: "application/json; charset=utf-8", //Added so ASP recognized JSON
traditional: true,
success: function (response) {
alert('Success!');
}
});
The controller you posted should recognize POST data already, but in case it doesn't, a simple [HttpPost] attribute is all you need:
[HttpPost]
public ActionResult GetFilterSession(List<FilterSessionModel> jsonFilters)
{
//Do things
return Json(false, JsonRequestBehavior.AllowGet);
}

javascript or ajax call never type cast the object. . .you need to set type of the controller side parameter either string or List else you can also set the Object type. . If you modified codein that way.. .Your code definitely work !!!

$.ajax({
url: "/FilterSessions/GetFilterSession",
type: "GET",
dataType: "json",
data:JSON.stringify({ 'jsonFilters': jsonFilters}),
contentType: 'application/json; charset=utf-8',
success: function (response) {
//Do your action
}
});

Related

Ajax call to MVC controllers

I'm trying to pass some data with ajax call to a c# mvc controller. Even though the task should be straight forward, I am unable to get the mvc controller to read the data I'm passing through the ajax call....
I've implemented the following code within my MVC controller
[HttpPost]
public string tt(string o)
{
return o;
}
[HttpPost]
public string tt2(string o)
{
return "lala";
}
And I'm triggering the following ajax calls from the browser
$.ajax({
url: "/Home/tt2",
type: "POST",
contentType: "application/json;",
data: JSON.stringify({ o: 'asdas'}),
success: function(e){console.log(e+' correct');},
error: function(e){console.log(e+' incorrect');}
});
$.ajax({
url: "/Home/tt",
type: "POST",
contentType: "application/json;",
data: JSON.stringify({ o: 'asdas'}),
success: function(e){console.log(e+' correct');},
error: function(e){console.log(e+' incorrect');}
});
As a result when running the first ajax call the result is
lala correct
And for the second ajax call, the result is
undefined correct
In the mean time these are some stuff I tried
Adding dataType: "json", to the ajax call
Changing the string data from {o: 'asdas'} to 'asdas'
Removing the JSON.stringify
Adding the charset=utf-8 to the contentType
Changing the ajax call type and MVC controller method from POST to GET to PUT
Changing the MVC controller method parameter from string to int
Removing the error method from the ajax call
Changing the data from data: {o: 'asdas'} to data: {"o":"asdas"}
Changing the data from data: {"o":"asdas"} to data: JSON.stringify({"o":"asdas"})
I know that simple string or int can be passed through the URL as query strings but it would be an issue when passing a list of objects..
Something aside is that the call is being done correctly to the URL because when I set a breakpoint within the called method, it does get triggered but the parameter always is null..
Any thoughts on how to make ajax call work?
try:
[HttpPost]
public string tt([FromBody]string o)
{
return o;
}
Your request should be like this:
$.ajax({
url: '#Url.Action("tt", "Home")',
data: {
"o": "asdasdas"
},
cache: false,
type: "POST",
success: function (response) {
},
error: function (xhr) {
}
});

Pass int to webapi

I know this has been asked a thousand times. But I can't find my error. I narrowed it down by testing it without a parameter, which worked and then tried various things. Like, get or post, [FromBody] or not. etc.
Perhaps I should just show my code or I should stop for today and just celebrate that it is almost weekend.
[HttpGet] // also tried post instead of get
public HttpResponseMessage Get(int id)
{
return Request.CreateResponse(HttpStatusCode.OK); // breakpoint set, not hit
}
My Js code:
var myObj = {};
myObj["id"] = parseInt(id);
var json = JSON.stringify(myObj);
alert(json); // display: { id = 2134 }, seems fine to me
$.ajax({
type: "GET", // also tried post
dataType: "json",
url: '/api/CheckPossible/Get',
data: json,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function () {
alert('success');
},
error: function () {
alert('failure');
}
});
I have received a lot of bad requests (400) and I did got it to work without a parameter. So it is not a routing issue.
edit
$.ajax({
type: "GET",
dataType: "json",
url: '/api/CheckPossible/Get/?id=1234', // also tried Get?id=1234
contentType: "application/json; charset=utf-8",
success: function () {
alert('success');
},
error: function () {
alert('failure');
}
});
Did not work. Perhaps I am missing something else too
You can't pass a http message body to a GET method, you have to pass parameters either in the URL or in the header. For a web api you should pass them in the URL and you can do this as a query string or as part of the URL.
To get it to work with the query string change the url to
url: '/api/CheckPossible/?id=' + myObj["id"],
leave out the data as this won't do anything with get.
If you want to make the parameter a part of the URL then change your route to include it. I prefer the Route attribute for flexible routing, you can also change the global routing scheme.
[HttpGet] // also tried post instead of get
[Route("api/CheckPossible/{id:int}"]
public HttpResponseMessage Get(int id)
{
}
and change your url to
url: '/api/CheckPossible/' + myObj["id"]

ajax post data is null in controller asp.net mvc 5

I try to send a JSON object back to the server. This is my AJAX call
function SaveData() {
var model = []
debugger
$.each($('.Money'), function (i, item) {
model.push({
Money: $('.Money').eq(i).val(),
Day: $('.Day').eq(i).val(),
Note: $('.Note').eq(i).val()
});
})
$.ajax({
url: '#Url.Action("Create")',
contentType: "application/json",
async: true,
data: { partnerDeposit: JSON.stringify(model) },
type: 'POST',
dataType: 'json',
succsess: function () {
}
})}
This is the method in the controller which is being called:
enter image description here
https://i.stack.imgur.com/FqEt9.png
The problem I have is that always the json variable from above is an empty object. The success function gets called but when I debug the json var is displayed as empty.
Please tell me what I am doing wrong. Thank you.
Try adding the partnerDeposit to the JSON.stringify call like this:
$.ajax({
url: '#Url.Action("Create")',
contentType: "application/json",
async: true,
data: JSON.stringify({partnerDeposit: model}),
type: 'POST',
dataType: 'json',
succsess: function () {
}
})
I haven't found this answer anywhere else so I had to discover it through experimentation. Hopefully this will help someone.
You'll find that in your controller, it's receiving a Request.Form object and if you look in Request.Form[0] you'll find your data. The reason that there's data in the form but MVC is seeing it as null is that the key to the form element being POSTed is "" (blank).
So client side, you have to set content type properly, and precede your data with something like "myData=" + JSON.stringify(myJSONObject), where "myData" is the key name you are adding, like so:
$.ajax({
type: "POST",
url: URL,
data: "myData="+JSON.stringify(myJSONObject),
contentType: "application/x-www-form-urlencoded; charset=utf-8"
On the server side, your [HttpPost] endpoint has to have as its input a variable with the same name as the key you declared in your AJAX, like so:
`
[HttpPost]
[Authorize]
public ActionResult Index (string myData) // <-- var name matches AJAX
{
// de-serialize data into server-side object using
// JSONConvert.DeserializeObject
}
`

Asp.net MVC 5 Modelbinding multiple JSON objects (knockoutjs)

Ok. I've encountered a problem that i just can't understand.
First of all, i'm trying to post several ko.observableArrays to the controller as JSON and modelbinding them seperately. When i post only one and don't name it in the data attribute of .ajax it posts just fine and modelbinds flawlessly.
This is my a snippet from my viewModel and is how i am attempting to post the two JSON objects.
self.timeRanges = ko.observableArray();
self.geoRequirements = ko.observableArray();
self.saveWorkWish = function() {
$.ajax({
url: "#Url.Action("SaveWorkWish")",
type: "POST",
contentType: 'application/json; charset=utf-8',
data: {
timeRanges: ko.toJSON(self.timeRanges()),
geoRequirements: ko.toJSON(self.geoRequirements())
},
complete: function (data) {
console.log(data);
}
});
};
My Action
public JsonResult SaveWorkWish(IList<JSONTimeRanges> timeRanges, IList<JSONGeoRequirements> geoRequirements)
{
// do stuff
}
I get this exception:
Invalid JSON primitive: timeRanges.
Interesting to note is that, when i do:
$.ajax({
url: "#Url.Action("SaveWorkWish")",
type: "POST",
contentType: 'application/json; charset=utf-8',
data: ko.toJSON(self.timeRanges()),
complete: function (data) {
console.log(data);
}
});
And
public JsonResult SaveWorkWish(IList<JSONTimeRanges> timeRanges)
{
// do stuff
}
It works just fine.
Lastly a thing that i noticed, and is likely the cause of the error is that:
When i post 2 Jsons like in the example,
this is what chrome tells me i post:
timeRanges=%5B%7B%22startDate%22%3A%2214-09-2014%22%2C%22endDate%22%3A%2220-09-2014%22%2C.....etc..
and in the working example:
it is a well formated and readable JSON object.
So it seems like the error is indeed correct and that i am not sending valid JSON to the controller.
But..what am i doing wrong?
Try to convert observables to JSON first and then convert the whole object to json string:
data: JSON.stringify({
timeRanges: ko.toJS(self.timeRanges()),
geoRequirements: ko.toJS(self.geoRequirements())
}),

Trivial JQuery $.ajax Json Post to ASP.NET MVC2 controller: Cannot get Controller to see JSON (or anything)

I went through dozens of answers to figure out the trick to posting data from $.ajax to a parameter in MVC 2's Controller. Here's as far as I got:
BTW this works if you use a GET, but fails as a POST. How would I fix it?
$(document).ready(function () {
$.ajax({
type: "POST",
url: "/Home/Get",
data: {value:'9/14/2010 12:00:00 AM'},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert(result.value);
}
});
});
And this is my MVC 2 Controller:
public class strange
{
public string value { get; set; }
}
public JsonResult Get(strange o)
{
var b = new strange { value = "return" };
return Json(b, JsonRequestBehavior.AllowGet);
}
Upon POST, o's "value" is null. Changing POST to GET, o's "value" is "9/14/2010 12:00:00 AM".
How do I get the POST to work with $.ajax?
Did anyone ever post a guide to getting JSON working with MVC2 data validation when returning JSON from the client? I know they had that in their MVC 2 futures a while ago.
The data which you send to the ASP.NET MVC Controller should not be JSON encoded. So you should just remove the line
contentType: "application/json; charset=utf-8",
from the $.ajax request and your program will work.
You need to pass JSON to the controller, and it's looking for a strange object, all you're currently passing is a string called value, instead your data should look like this:
{ strange: { value:'9/14/2010 12:00:00 AM'} }
Notice how strange is not an object with the value property the server is looking for. But, it'll expect this as a string, so just use JSON.stringify() (use JSON2 if needed for other browsers, e.g. < IE8):
data: JSON.stringify({ strange: { value:'9/14/2010 12:00:00 AM'} }),

Categories