I’m trying to figure out the model binding in MVC3. Look at this example.
Here’s the controller code:
public ActionResult Index()
{
Person person = new Person{ Name = "Test" };
return View(person);
}
[HttpPost]
public string Edit(Person personModel)
{
return string.Format("From server: {0}", personModel.Name);
}
And here’s the html/javascript bit:
@model MCV3.Test.Models.Person
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
$(document).ready(function (){
var model = @Html.Raw(Json.Encode(Model));
$.ajax({
url : "/Person/Edit",
type: "Post",
datatype: "json",
data : model,
success: function (data) {
$("#result").text(data);
}
});
});
</script>
</head>
<body>
<label id="result"></label>
</body>
</html>
The code above works, but if I change data setting of the ajax call to this:
$.ajax({
url : "/Person/Edit",
type: "Post",
datatype: "json",
data : {personModel : model},
success: function (data) {
$("#result").text(data);
}
});
it doesn’t work any more: the model is of the correct type, but the name property is null.
In the example that works, the post parameters are:
Name Test
Name=Test
But in the example that doesn’t work, they are:
personModel[Name] Test
personModel%5BName%5D=Test
It seems like MVC can’t serialize the request if it looks like this: personModel[Name] Test
Is there any way to solve this without writing a custom binder?
When MVC binding tries to create and populate a
Personobject to pass to yourEditaction, it tries to find values for all the settable properties on thePersonobject; in this case theNameproperty. It therefore looks in the form data, query string data (etc.) for a name value pair with the key ‘Name’. Your working example has one, your non-working example doesn’t.If you want to post data in this format you could create a custom
ValueProviderwhich parses the data and returns values based on what it finds.