第一个html helper生成客户端验证属性,而第二个则不 [英] First html helper generates client-side validation attributes, while the second one doesn't

查看:87
本文介绍了第一个html helper生成客户端验证属性,而第二个则不的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有这个模型:

public class Person
{
    public bool IsApproved { get; set; }
}

在编写此代码时,我正在尝试使用check类型渲染input:

And whis this codes, I am trying to render input with check type:

@Html.CheckBoxFor(x => x.IsApproved)
@Html.CheckBox("IsApproved")

但是,结果却不同:

// CheckBoxFor result
<input data-val="true" data-val-required="The IsApproved field is required." id="IsApproved" name="IsApproved" type="checkbox" value="true">
<input name="IsApproved" type="hidden" value="false">

// CheckBox result
<input id="IsApproved" name="IsApproved" type="checkbox" value="true">
<input name="IsApproved" type="hidden" value="false">

如何以及为什么 ,第一个生成用于客户端验证的属性,而另一个不生成?

How and why, the first one generates attributes for client-side validation, while the other didn't?

更新:

Update:

交换@Html.CheckBoxFor@Html.CheckBox的顺序后,标记元素的顺序没有改变.

After swapping the order of @Html.CheckBoxFor and @Html.CheckBox, the order of markup elements didn't change.

推荐答案

CheckBox()帮助器不会呈现data-val属性,因为表单已经为同一属性呈现了CheckBoxFor().如果交换订单,则将为CheckBox()(而不是CheckBoxFor())呈现data-val属性.

The CheckBox() helper does not render thedata-val attributes because the form has already rendered CheckBoxFor() for the same property. If you swap the order, the data-val attributes would be rendered for CheckBox() (and not for CheckBoxFor()).

我的理解是,这会在解析表单时导致jquery.validation.unobtrusive潜在的(重复)问题.

My understanding is this would cause a potential (duplication) problem with jquery.validation.unobtrusive when parsing the form.

控件的html帮助器在内部调用HtmlHelperGetUnobtrusiveValidationAttributes()方法. 摘自源代码(我强调)

The html helpers for controls internally call the GetUnobtrusiveValidationAttributes() method of HtmlHelper. From the source code (my emphasis)

仅在启用非侵入式客户端验证的情况下渲染属性,然后仅在我们从未以这种形式对具有此名称的字段进行验证的情况下.另外,如果没有表单上下文,那么我们将无法呈现属性(我们无需将其附加到)

Only render attributes if unobtrusive client-side validation is enabled, and then only if we've never rendered validation for a field with this name in this form. Also, if there's no form context, then we can't render the attributes (we'd have no to attach them to)

public IDictionary<string, object> GetUnobtrusiveValidationAttributes(string name, ModelMetadata metadata)
{

这篇关于第一个html helper生成客户端验证属性,而第二个则不的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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