Javascript 为ajax文章手动调用MVC 3客户端验证
我正在创建一个MVC3Web应用程序。我希望在实体类上使用数据注释,然后在向服务器发回帖子之前使用不引人注目的客户端验证。这在写一篇普通文章时效果很好。如果任何字段无效,我将获得验证和验证摘要。但是,我想通过ajax和json发回信息。如何首先在客户端“手动”验证表单,然后将我的ajax帖子发送回服务器。下面是我的代码的摘要版本Javascript 为ajax文章手动调用MVC 3客户端验证,javascript,jquery,asp.net-mvc,validation,asp.net-mvc-3,Javascript,Jquery,Asp.net Mvc,Validation,Asp.net Mvc 3,我正在创建一个MVC3Web应用程序。我希望在实体类上使用数据注释,然后在向服务器发回帖子之前使用不引人注目的客户端验证。这在写一篇普通文章时效果很好。如果任何字段无效,我将获得验证和验证摘要。但是,我想通过ajax和json发回信息。如何首先在客户端“手动”验证表单,然后将我的ajax帖子发送回服务器。下面是我的代码的摘要版本 public class Customer { [Required(ErrorMessage = "The customer's first
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) %>
<% } %>
尝试:
这应该适用于jqueryajax和MSAjax调用。也可以尝试使用,否则它会自动为您处理此问题。我已经花了好几天时间研究MVC客户端验证: 不使用。单击“使用”。提交:
$("#MyForm").on('submit',function () {
if($("#MyForm").valid())
{
//Do ajax stuff
}
//Return false regardless of validation to stop form submitting
//prior to ajax doing its thing
return false;
});
我将添加一个更新,考虑取消事件而不是返回false(或者两者都做):
重要!!:
保罗的答案是问题的正确答案,而不是罗布博士的
尽管您可以使用valid()而不是validate().form()
但更重要的是,确实没有理由像Rob博士建议的那样限制您的代码,也就是说,没有。单击并仅使用。提交。这并不是解决问题的办法!解决这个问题的方法是在if语句中包装$.ajax(…)调用。即:
if($("#MyForm").valid())
{
//call to $.ajax or equivalent goes in here.
}
我认为这需要澄清,否则问题的真正答案将变得模糊。至少在我的情况下(MVC 5),还需要添加以下代码,否则。valid()
将始终返回true:
$(function () {
$(document).ajaxComplete(function(event, request, settings){
//re-parse the DOM after Ajax to enable client validation for any new form fields that have it enabled
$.validator.unobtrusive.parse(document);
});
}))
请参见$(YourForm).data('unobtrusiveValidation').validate()
它触发验证并返回一个布尔值,因此您可以在提交之前进行检查。.Valid()有效。i、 它告诉你你的表格是否有效。但是,仅此一项并不能帮助正确显示和隐藏消息。这是我的手动验证方法
function validate()
{
//valid() not only tells us whether the form is valid but
//also ensures that errors are shown !!!
if ($("form").valid())
{
//if the form is valid we may need to hide previously displayed messages
$(".validation-summary-errors").css("display", "none");
$(".input-validation-error").removeClass("input-validation-error");
return true;
}
else
{
//the form is not valide and because we are doing this all manually we also have to
//show the validation summary manually
$(".validation-summary-errors").css("display", "block");
return false;
}
}
我使用的是jqueryv2.1.4和jQuery.Validation v1.11.1。
我需要在页面呈现时触发验证。只有不到一个对我有用
$(document).ready(function () {
...
validateForm();
}
function validateForm() {`enter code here`
var elem = document.getElementById('btnSave');
elem.click();
}
$('#btnSave').click(function (evt) {
//evt.preventDefault();
var form = $('form');
if (form.valid()) {
//Ajax call here
}
//$(".validation-summary-errors").css("display", "block");
});
function Validate() {
// If no group name provided the whole page gets validated
Page_ClientValidate();
}
很好的解决方案。非常感谢你。在过去的几天里,我一直在浪费时间。另外,请务必在页面上引用jquery.validate.min.js和jquery.validate.unobtrusive.min.js,否则您的表单将没有.valid()方法。@juhan_h+1-完全同意您的意见。。。我总是忘记;-)-1.这个答案提出了一个错误的建议。见下面我的帖子。它之所以有效,是因为围绕ajax调用包装了if语句($(“#MyForm).valid()),而不是因为使用了.submit而不是.click。两者都使用没有问题!调用preventDefault()怎么样?使用单击的问题是,您仍然必须处理表单中的提交事件。如果您使用单击事件进行ajax调用,如果您不明确地处理该事件,它可能会被提交操作所压倒……我的解决方案是,我确信,我没有投票的许多解决方案之一是作为其他人的答案……正如我在我的帖子中所说的那样有一段时间,我试图让点击做一些它不想做的事情,但当我切换到提交时,它解决了“我的问题”“问题。很抱歉用这篇文章引起了大家的注意,但我想为过路人添加一些信息。更明显的问题应该是,您不必单击按钮来提交表单,这会导致跨浏览器出现一些奇怪的行为。如果用户点击表单字段上的enter键,浏览器可能会很好地查找submit按钮以触发单击事件。否则,它只需要提交表单而不需要点击事件,提交按钮就完蛋了。毕竟,如果出于某种原因您有多个提交按钮。。。它怎么知道应该点击哪个提交?@Aejay我同意。我几乎已经停止在任何使用Ajax调用的代码中使用
。不管怎样,我正在处理Ajax调用,不需要添加可能提交的问题。只需使用
并处理您想要的任何操作。正如我在下面的评论中提到的,如果您没有通过返回false显式地处理提交操作的取消,那么在单击中执行ajax调用可能会导致提交调用胜过ajax调用。。。这意味着解决方案需要编写两个函数而不是一个…@DrRob,您永远不应该返回false,您应该将jQuery事件捕获为param并调用preventDefault()。如果单击处理程序使用return false来阻止浏览器导航,则解释器可能无法到达return语句,浏览器将继续执行锚定标记的默认行为。这是导致问题的原因,而不是因为您使用的是单击vs提交。使用event.preventDefault()的好处是,您可以将其添加为处理程序中的第一行,从而确保锚的默认行为不会触发.evt.preventDefault();我喜欢这个,现在就一直使用它,而不是返回false。@Paul在搜索了很多之后,终于从你那里得到了答案。:)欢迎使用Stackoverflow,请添加此功能的原因。哇!!我已经找了很久了。终于偶然发现了这一点。谢谢!
$(function () {
$(document).ajaxComplete(function(event, request, settings){
//re-parse the DOM after Ajax to enable client validation for any new form fields that have it enabled
$.validator.unobtrusive.parse(document);
});
if(!$('#myform').data('unobtrusiveValidation').validate())
{
// add your extra custom logic
}
else
{
$('#myform').submit();
}
function validate()
{
//valid() not only tells us whether the form is valid but
//also ensures that errors are shown !!!
if ($("form").valid())
{
//if the form is valid we may need to hide previously displayed messages
$(".validation-summary-errors").css("display", "none");
$(".input-validation-error").removeClass("input-validation-error");
return true;
}
else
{
//the form is not valide and because we are doing this all manually we also have to
//show the validation summary manually
$(".validation-summary-errors").css("display", "block");
return false;
}
}
I tried all of the above solutions but none worked on MVC5.
$(document).ready(function () {
...
validateForm();
}
function validateForm() {`enter code here`
var elem = document.getElementById('btnSave');
elem.click();
}
$('#btnSave').click(function (evt) {
//evt.preventDefault();
var form = $('form');
if (form.valid()) {
//Ajax call here
}
//$(".validation-summary-errors").css("display", "block");
});
function Validate() {
// If no group name provided the whole page gets validated
Page_ClientValidate();
}