I'm trying to post data using jQuery Ajax to MVC action using the approach below. But inside the controller all model properties are always null. Not sure what I'm missing here.
.CSHTML
<form id="MyForm">
<input name="PersonName" type="text" />
<input name="Address" type="text" />
<select name="States" multiple="multiple">
<option value="TX">Texas</option>
<option value="OK">Oklahoma</option>
<option value="OH">Ohio</option>
</select>
<select name="Status">
<option value="1">Active</option>
<option value="2">Deleted</option>
<option value="3">Pending</option>
</select>
<input type="button" value="Save" id="Save" />
JavaScript
$(function () {
$("#Save").click(function (e) {
var dataToPost = $("#MyForm").serialize()
$.ajax(
{
type: "POST",
data: JSON.stringify(dataToPost),
url: "Working/Save",
contentType: 'application/json; charset=utf-8'
})
})
})
Controller
public class WorkingController : Controller
{
// GET: Working
public ActionResult Index()
{
return View();
}
public ActionResult Save(WorkingModel model)
{
// All model properties are null here????
return Json("Success");
}
}
Model
public class WorkingModel
{
public string PersonName { get; set; }
public string Address { get; set; }
public string[] States { get; set; }
public string Status { get; set; }
}
EDIT1
I have added the model above. Here the serialized data and JSON stringify data when I click on save.
Serialized data
"PersonName=Foo&Address=123+Test+Drive&States=TX&Status=1"
After JSON.Stringify
"\"PersonName=Foo&Address=123+Test+Drive&States=TX&Status=1\""
I have tried adding HttpPost attribute and [FromBody] attribute with no luck.
I don't think I have to change the return type from ActionResult to JsonResult.
Also the URL is correct because the debugger is hitting inside the action method where I can QuickWatch the model properties.
Note that it works if I create JSON object and post it like below:
var dataToPost = {
PersonName:'Foo',
Address: '123 Test Drive',
State: 'TX',
Status: 1
}