One of the most common questions in Asp.Net MVC development community is "How to post a strongly type model using jQuery?"
Developers new to the framework often attempt to hijack the submit event and post the model to an MVC Action, then start scratching their heads and wonder why all of the posted model properties are null.The short answer is serialization.
In order to populate the model's properties, you have to serialize the posted form on the client side using jQuery's serialize function.Note, the $(this).serialize() call in the body of the ajax function.
In the following simple demo, a Person model is posted to ActionResult:
<form id="frmCreateUser" action="" method="post">
<div class="bordered" id="UserForm">
<fieldset>
<legend>User Information</legend>
@Html.LabelFor(m => m.UserName, "UserName:")
@Html.TextBoxFor(m => m.UserName, new { @class = "text-box" })
@Html.ValidationMessageFor(m => m.UserName) <br />
@Html.LabelFor(m => m.Password, "Password:")
@Html.PasswordFor(m => m.Password, new { @class = "text-box" })
@Html.ValidationMessageFor(m => m.Password) <br />
@Html.LabelFor(x => x.Email, "Email:")
@Html.TextBoxFor(x => x.Email)
@Html.ValidationMessageFor(x => x.Email)<br />
<input id="createButton" type="submit" value="Create" />
</fieldset>
</div>
</form>
<script type="text/javascript">
$(document).ready(function () {
$("#frmCreateUser").submit(function (event) {
$.ajax(
{
url: '@Url.Action("CreateUser", "dashboard",new {area="Security"})',
dataType: 'json',
data: $(this).serialize(),
type: 'POST',
success: function (result) {
alert(result);
},
error: function (xhr) {
alert(xhr.statusText);
}
});
event.preventDefault();
});
});
</script>
The ActionResult where the person model is posted:
[HttpPost]
public JsonResult CreateUser(Person model)
{
bool isSuccess = false;
MembershipCreateStatus createStatus;
Membership.CreateUser(model.UserName, model.Password, model.Email, null, null, true, null, out createStatus);
return Json(createStatus.ToString(), JsonRequestBehavior.AllowGet);
}