Today I needed to post a strongly typed model using jquery and MVC 3.0 using razor engine.
My first thought was this should be easy, just hijack the submit button and send the request. well to my surprise, I was wrong :-)
The post was processed OK but my model didn't have ant of its properties populated.all of model's properties were null
The solution was to hijack the form's submit event and post the serialized form using jQuery's ajax function.
Note, the $(this).serialize() call in the body of the ajax function.
HTML and javascript
<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>
<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>
here is my action.
[HttpPost]
public JsonResult CreateUser(User 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);
}