Let's say I have this model:
public class Person
{
public bool IsApproved { get; set; }
}
And whis this codes, I am trying to render input
with check
type:
@Html.CheckBoxFor(x => x.IsApproved)
@Html.CheckBox("IsApproved")
But, the results are different:
// 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:
After swapping the order of @Html.CheckBoxFor
and @Html.CheckBox
, the order of markup elements didn't change.
The
CheckBox()
helper does not render thedata-val
attributes because the form has already renderedCheckBoxFor()
for the same property. If you swap the order, thedata-val
attributes would be rendered forCheckBox()
(and not forCheckBoxFor()
).My understanding is this would cause a potential (duplication) problem with jquery.validation.unobtrusive when parsing the form.
The html helpers for controls internally call the
GetUnobtrusiveValidationAttributes()
method ofHtmlHelper
. From the source code (my emphasis)