我正在创建一个 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
});
Try:
//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 http://nuget.org/packages/TakeCommand.js or https://github.com/webadvanced/takeCommand https://github.com/webadvanced/takeCommand它会自动为您处理这个问题。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)