ASP.NET MVC不显眼的验证 - 为什么需要形式方面? [英] ASP.NET MVC Unobtrusive validation - why form context is needed?

查看:115
本文介绍了ASP.NET MVC不显眼的验证 - 为什么需要形式方面?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图启用动态创建的项目不显眼的JavaScript验证。与JavaScript的问题已经解决了另一个问题,SO这里不是这种情况。

I'm trying to enable unobtrusive javascript validation for dynamically created items. The problem with javascript was already solved in another SO question and this is not the case here.

在这种情况下,项目的动态创建只是克隆是主要形式之外产生的一个空的项目。

Dynamic creation of items in this case is just cloning of one empty item that is generated outside of the main form.

问题是,如果我用html佣工像TextBoxFor,CheckBoxFor,... HTML表单元素,然后才能属性需要验证以外的工作(例如:数据VAL-要求)不会产生。

The problem is that if I use html helpers like TextBoxFor, CheckBoxFor, ... outside the html form element then attributes required in order for the validation to work (eg. data-val-required) are not generated.

我已经检查了MVC源$ C ​​$ C并没有返回空属性列表,如果 FormContext 为空行。 (这没有抛出异常)

I've already checked the MVC source code and there is a line that returns empty attribute list if FormContext is null. (this throws no exceptions)

为什么?

推荐答案

您可以手动假一种形式的上下文。例如,如果你有不包含某些局部视图<形式> 元素和使用AJAX来重新生成一些输入元素,你可以做到这叫做:

You could manually fake a form context. For example if you had some partial view which doesn't contain a <form> element and which is called using AJAX to regenerate some input elements you could do this:

@model MyViewModel
@{
    ViewContext.FormContext = new FormContext();
}

@Html.LabelFor(x => x.Foo)
@Html.EditorFor(x => x.Foo)
@Html.ValidationMessageFor(x => x.Foo)

在相应的输入元素现在有拥有的数据 - * 属性。但是,这可能还不够。如果你只刷新(使用AJAX)只有一部分的&LT;形式&GT; 但实际上没有更换表单元素在DOM调用 $。 validator.unobtrusive.parse 是不够的。您需要删除关联到这个元素的任何previous验证:

The corresponding input elements will now posses the data-* attributes. But that might not be enough. If you are only refreshing (using AJAX) only a portion of the <form> but not actually replacing the form element in the DOM calling $.validator.unobtrusive.parse wouldn't suffice. You need to remove any previous validations associated to this element:

success: function(result) {
    // we are replacing only a portion of the form
    $('#somePartOfTheForm').html(result);

    $('form').removeData('validator');
    $('form').removeData('unobtrusiveValidation');
    $.validator.unobtrusive.parse('form');   
}

这篇关于ASP.NET MVC不显眼的验证 - 为什么需要形式方面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆