问题描述
假设我有这个模型:
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帮助器在内部调用HtmlHelper
的GetUnobtrusiveValidationAttributes()
方法. 摘自源代码(我强调)
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生成客户端验证属性,而第二个则不的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!