helper生成客户端验证属性

helper生成客户端验证属性

本文介绍了第一个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)

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

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

09-03 15:10