Reputation: 879
I am having a simple issue which is taking way to long to figure out. I cant seem to get data from JS into MVC.
JS:
var stuff = [{a: 1, b: "Low"}, {a: 5, b:"High"}];
$.ajax({
url: '@Url.Action("Action")',
type: 'POST',
data: JSON.stringify({ stuff: stuff }),
traditional: true
});
MVC
public enum Level
{
High = 10,
Normal = 5,
Low = 1
}
...
public class MyModel
{
public int a { get; set; }
public Level b { get; set; }
}
...
public ActionResult Action(List<MyModel> stuff){
//stuff is always null no matte what I try?
....
}
I am not sure where my problem actually is, as this is surprisingly hard to debug.
Upvotes: 2
Views: 6365
Reputation: 218892
Specify the contentType
properpty on your ajax call and it should work fine.
When sending data to server using $.ajax, default contentType value is "application/x-www-form-urlencoded; charset=UTF-8
" . Since we are sending JSON data, We should specify it.
var stuff = [{a: 1, b: "Low"}, {a: 5, b:"High"}];
$.ajax({
url: '@Url.Action("Action")',
type: 'POST',
data: JSON.stringify({ stuff: stuff }),
contentType:"application/json", //This is the new line
traditional: true
}).done(function(res) {
console.log("Result came back");
});
Upvotes: 4
Reputation: 306
I just realized this is the issue:
data: JSON.stringify({ stuff: stuff })
change it to:
data: JSON.stringify(stuff)
Upvotes: 0