[英]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? 任何人都知道jaxaxax post的工作示例,其中从服务器返回的验证消息突出显示了相关的表单字段?
Should the form be a partial view? 表格应该是局部视图吗? Is it possible to make use of modelstate? 是否可以使用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. 正如您所建议的,最简单的方法是将整个表单放入部分视图中,并向返回该部分的控制器动作执行ajax请求。 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. 另一种选择是发布到控制器操作,该操作将所有错误消息放入JSON数组中,并将其传递到视图。 Then using javascript you could loop through the error messages and show them. 然后,使用javascript可以遍历错误消息并显示它们。
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");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.