Reputation: 322
I am trying to bind json to my model in ASP .net MVC 4. The model does get created but the properties are not filled.
My javascript:
$.ajax({
type: 'POST',
url: "/Admin/" + method,
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(form.serializeArray()),
success: function (data) {
if (data.Success == true) {
}
}
});
My Class:
public class Taxes {
public int Id { get; set; }
public string Name { get; set; }
public decimal Rate { get; set; } }
My Method:
[HttpPost]
public JsonResult AddTax(Taxes tax)
{
return Json(new { Success = true, tax.Id });
}
The Json:
[{"name":"Id","value":"1"},{"name":"Name","value":"fsdfs"},{"name":"Rate","value":"18"}]
The result is:
Id = 0
Name = Null
Rate = 0
Upvotes: 0
Views: 117
Reputation: 11177
Well you've written what your problem is, but you're just not reading it. Your call to JSON.stringify(form.serializeArray()) is generating this for you:
[{"name":"Id","value":"1"},{"name":"Name","value":"fsdfs"},{"name":"Rate","value":"18"}]
Which can only be mapped to something like this:
IEnumerable<SampleClass> model
Where SampleClass has properties:
public class SampleClass
{
public string name {get;set;}
public string value {get;set;}
}
You need different kind of method, one which will:
JSON.stringify will then generate proper JSON representation of your Taxes class.
Check the implementation here:
https://github.com/hongymagic/jQuery.serializeObject
Upvotes: 2