Help with jquery ajax posting and server-side validation messages
Anyone know of a working sample of jquery axax post with validation messages being returned from the server that highlight the relevant form fields?
Should the form be a partial view? Is it possible to make use of modelstate?
开发者_运维问答Cheers
As you've suggested the easiest way is to put the whole form into a partial view and perform an ajax request to a controller action which returns this partial. If you use validation helpers inside this partial, error messages will be shown.
Another alternative is to post to a controller action which puts all error messages inside a JSON array and passes it along to the view. Then using javascript you could loop through the error messages and show them.
Example attached:
Partial:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<div id="subContent">
<fieldset>
<legend>Subscribe</legend>
<form id="subForm" method="post" action="<%= Url.Action("Subscribe") %>">
<%= Html.ValidationSummary("Subscribe was unsuccessful. Please correct the errors and try again.") %>
<input type="text" name="name" id="name" /><%= Html.ValidationMessage("name", "*") %>
<input type="submit" />
</form>
</fieldset>
</div>
<script language="javascript" type="text/javascript">
$(document).ready(function() {
$('#subForm').live('submit', function() {
$.post($(this).attr('action'), $(this).serialize(), function(data) {
$("#subContent").replaceWith($(data));
});
return false;
});
});
</script>
Controller:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Subscribe(string name)
{
ModelState.AddModelError("name", "You must enter a name");
return PartialView("SubscribeForm");
}
精彩评论