我正在创建一个 MVC 3 网络应用程序。我想在我的实体类上使用数据注释,然后在回发到服务器之前使用不显眼的客户端验证。这在制作常规帖子时效果很好。如果任何字段无效,我会得到验证和验证摘要。但是,我想通过 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
});
最佳答案
尝试:
//using the form as the jQuery selector (recommended)
$('form').submit(function(evt) {
evt.preventDefault();
var $form = $(this);
if($form.valid()) {
//Ajax call here
}
});
//using the click event on the submit button
$('#buttonId').click(function(evt) {
evt.preventDefault();
var $form = $('form');
if($form.valid()) {
//Ajax call here
}
});
这应该适用于 jQuery ajax 和 MSAjax 调用。也可以尝试使用 http://nuget.org/packages/TakeCommand.js或 https://github.com/webadvanced/takeCommand它会自动为您处理。
关于javascript - 为 ajax 帖子手动调用 MVC 3 客户端验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5127813/