Reputation: 2399
I'm using serialize
and JSON.stringify
methods to make an Ajax call to my ASP.NET MVC application. MVC is unable to bind the model.
This is my JS code and strongly-typed view:
<script>
function saveDetails() {
jsonObj = $('#rdform').serialize();
$.ajax({
method: "POST",
url: "R/SaveDetail",
contentType: 'application/json; charset=utf-8',
dataType: "json",
data: JSON.stringify(jsonObj)
});
}
</script>
<form id="rdform">
<div>
<div>
@Html.LabelFor(m => m.LiIdH)
@Html.TextBoxFor(m => m.LiIdH)
</div>
<div>
@Html.LabelFor(m => m.LiIdR)
@Html.TextBoxFor(m => m.LiIdR)
</div>
</div>
<input type="button" onclick="saveDetails()" />
</form>
The request's payload looks like this:
"LiIdH=1&LiIdD=&LiIdR=2"
And this is my Action method:
public bool SaveDetail(Detail detail)
Have I missed something?
Upvotes: 1
Views: 3168
Reputation: 183
The reason you are running into trouble is because of your use of both serialize and JSON.stringify. form.serialize returns a string value, which when passed to JSON.serialize gets wrapped with an extra pair of quotes. The easiest way for you to invoke your action method would be to remove your call to JSON.stringify and also remove the contentType option of the ajax call and go with the default, as shown below:
<script>
function saveDetails() {
$.ajax({
method: "POST",
url: "R/SaveDetail",
dataType: "json",
data: $('#rdform').serialize()
});
}
</script>
Upvotes: 4