asp.net-mvc 不显眼的验证不适用于 Ajax.BeginForm

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8927933/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 01:41:44  来源:igfitidea点击:

Unobtrusive validation doesn't work with Ajax.BeginForm

asp.net-mvcasp.net-mvc-3unobtrusive-validation

提问by Oleksandr Fentsyk

I have View with Model1 where I put Ajax.BeginForm()and in this View i have PartialView with Model2 where i put Ajax.BeginForm(). So only in first form working unobtrusive validation. Why only in first form working validation?

我在 Model1 中放置Ajax.BeginForm()了 View,在这个 View 中我在 Model2 中放置了 PartialView Ajax.BeginForm()。所以只能以第一种形式工作unobtrusive validation。为什么只在第一形式的工作验证中?

first View

第一次查看

@model Model1

@using (Ajax.BeginForm("Action1","Controller",null,new AjaxOption(){ onSuccess = "alert('=)')"},null)
{

   <intput type="submit" value="Save" />
}


Model2 model2 = new Model2();
@Html.EditorFor(m=>model2)

**In Model2 view i have. **

**在 Model2 视图中我有。**

@model Model2 
@using (Ajax.BeginForm("AddStreet","Controller",new AjaxOption(){onSuccess = "alert('=)'")},option,null)
{

        @Html.LabelFor(m => Model.Name):
        @Html.TextBoxFor(m => Model.Name)
        @Html.ValidationMessageFor(m => Model.Name)

       <intput type="submit" value="Save" />
}

Thanks @Darin Dimitrov for answer.

感谢@Darin Dimitrov 的回答。

回答by Darin Dimitrov

That's because the second view is loaded with AJAX at a later stage and you need to call $.validator.unobtrusive.parse(...)immediately after its contents is injected into the DOM in order to enable unobtrusive validation. Look at the following blog postfor more details.

这是因为第二个视图在稍后阶段使用 AJAX 加载,您需要$.validator.unobtrusive.parse(...)在其内容注入 DOM 后立即调用,以启用不显眼的验证。有关更多详细信息,请查看以下博客文章

So in your case, instead of alertingin the OnSuccesscallback of the first AJAX call, subscribe to a javascript function which will invoke this method:

因此,在您的情况下,不要在第一个 AJAX 调用的回调中发出警报,而是OnSuccess订阅将调用此方法的 javascript 函数:

@using (Ajax.BeginForm(
    "Action1",
    "Controller",
    null,
    new AjaxOptions { 
        OnSuccess = "onSuccess",
        UpdateTargetId = "result"
    },
    null)
)
{
    <input type="submit" value="Save" />
}

and then in your javascript file:

然后在你的 javascript 文件中:

var onSuccess = function(result) {
    // enable unobtrusive validation for the contents
    // that was injected into the <div id="result"></div> node
    $.validator.unobtrusive.parse($(result));
};

回答by dperez

You need to add those 2 files in you Partial Vieweven if it is already in the Shared/_Layout.cshtml:

即使它已经在Shared/_Layout.cshtml中,您也需要在Partial View 中添加这 2 个文件:

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>

Or place this in your Partial:

或者把它放在你的Partial 中

<script type="text/javascript" language=javascript>
    $.validator.unobtrusive.parse(document);
</script>

回答by ViRuSTriNiTy

The answer of Darin Dimitrov only works when validate()of the jquery validate pluginhas not been called until the Ajax success handler is called. I can't think of a scenario where this could be the case, thus i wonder why the answer was accepted as correct.

达林季米特洛夫的答案只能当validate()jquery validate plugin还没有被调用,直到阿贾克斯成功处理程序被调用。我想不出可能是这种情况的场景,因此我想知道为什么答案被认为是正确的。

Perhaps a change in the jquery validate code in the past now causes the following issue:

也许过去对 jquery 验证代码的更改现在会导致以下问题:

The issue is that validate()executes the following line first

问题是validate()首先执行以下行

// Check if a validator for this form was already created
var validator = $.data( this[ 0 ], "validator" );
if ( validator ) {
  return validator;

which means that the validator object is returned when validate() is called without and further handling of the options passed.

这意味着在调用 validate() 时返回验证器对象,而无需进一步处理传递的选项

This also means that a later call to $.validator.unobtrusive.parse(...)or $.validator.unobtrusive.parseElement(...)which executes a

这也意味着稍后调用$.validator.unobtrusive.parse(...)or$.validator.unobtrusive.parseElement(...)执行

$form.validate(this.options) <- this.options holds the new rules parsed from HTML

to update the options of the validator has no effect because the options are not processed at all.

更新验证器的选项无效,因为根本不处理选项。

The solution here is to update the validator manually like

这里的解决方案是像这样手动更新验证器

var $htmlCode = $("your html");

$.validator.unobtrusive.parse($htmlCode, true); // true means no validate() call

// now get the validation info collected in parse()
var validationInfo = $form.data("unobtrusiveValidation"); 

var $validator = $form.validate(); // get validator and ...
$validator.settings.rules = validationInfo.options.rules; // ... update its rules
$validator.settings.messages = validationInfo.options.messages; // ... update its messages

Revalidating the form (e.g. clicking submit) should now result in the expected results.

重新验证表单(例如单击提交)现在应该会产生预期的结果。

Here is a full example witch also includes code from the already accepted answer:

这是一个完整的示例女巫还包括来自已经接受的答案的代码:

Razor

剃刀

@using (Ajax.BeginForm(
    "Action1",
    "Controller",
    null,
    new AjaxOptions { 
        OnSuccess = "onSuccess",
        UpdateTargetId = "result"
    },
    null)
)
{
    <input type="submit" value="Save" />
}

Javascript

Javascript

var onSuccess = function(result) {
    var $htmlCode = $(result);

    $.validator.unobtrusive.parse($htmlCode, true); // true means no validate() call

    // now get the validation info collected in parse()
    var validationInfo = $form.data("unobtrusiveValidation"); 

    var $validator = $form.validate(); // get validator and ...
    $validator.settings.rules = validationInfo.options.rules; // ... update its rules
    $validator.settings.messages = validationInfo.options.messages; // ... update its messages
};

--

——

As a side note, manually updating the validator is also possible by using the rules()method like

作为旁注,也可以使用rules()类似的方法手动更新验证器

$yourHtmlField.rules( "add", {
  required: true,
  messages: {
    required: "Required input"
  }
});

as this directly updates the rules of the validator without the unobtrusive stuff. But then the data-val attributes are rendered useless.

因为这直接更新了验证器的规则而没有不显眼的东西。但是随后 data-val 属性变得无用。

回答by gdoron is supporting Monica

You have to add a reference to jquery.unobtrusive-ajax.jsto enable the validation within Ajax Form

您必须添加一个引用以jquery.unobtrusive-ajax.js在其中启用验证Ajax Form

Something like this:

像这样的东西:

<script type="text/javascript" src="/Scripts/jquery.unobtrusive-ajax.js"></script>

回答by JeremyFromNaples

This solution worked best for me.

这个解决方案最适合我。

$.validator.unobtrusive.parse(document);