我正在创建一个 MVC 3 Web 应用程序。我想在我的实体类上使用数据注释,然后在回发到服务器之前使用不显眼的客户端验证。这在发布常规帖子时效果很好。如果任何字段无效,我会得到验证和验证摘要。但是,我想通过ajax和json回发信息。我怎样才能“手动”验证客户端的表单,然后让我的 ajax 回发到服务器。下面是我的代码的总结版本。
public class Customer
{
[Required(ErrorMessage = "The customer's first name is required.")]
public string FirstName { get; set; }
[Required(ErrorMessage = "The customer's last name is required.")]
public string LastName { get; set; }
}
<% using (Html.BeginForm()) { %>
<%: Html.LabelFor(model => model.FirstName, "First Name")%>
<%: Html.TextBoxFor(model => model.FirstName, new { @class = "TextBox", id = "Customer.FirstName" })%>
<%: Html.ValidationMessageFor(model => model.FirstName, "*")%>
<%: Html.LabelFor(model => model.LastName, "Last Name")%>
<%: Html.TextBoxFor(model => model.LastName, new { @class = "TextBox", id = "Customer.LastName" })%>
<%: Html.ValidationMessageFor(model => model.LastName, "*")%>
<div id="CustomerEditSave" class="Button CustomerEditButtons" style="margin-right:40px;">
<a href="#">Save</a>
</div>
<%: Html.ValidationSummary(true) %>
<% } %>
我试过这段代码,但它只验证名字,不显示验证摘要。
$("#CustomerEditSave").click(function () {
$(form).validate();
//Ajax call here
});