By Farhad Jabiyev


2015-03-14 10:36:40 8 Comments

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.

1 comments

@user3559349 2015-03-14 11:30:13

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()).

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 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)
{

@Farhad Jabiyev 2015-03-14 11:36:17

Thanks for a nice explanation. This is an answer.

@Farhad Jabiyev 2015-07-24 10:20:05

Hi @Stephen, Sorry for distrubing again. Several days ago I have posted one question about one problem which I metAsp.net MVC. Have youu any idea about it? Could you please look at it. Here is the question.

@user3559349 2015-07-24 10:31:36

@FarhadJabiyev, No time now, but I'll take a look tomorrow morning :)

@Farhad Jabiyev 2015-07-24 10:35:25

:) Ok, sorry for disturbing again. Thanks.

Related Questions

Sponsored Content

0 Answered Questions

Client side validation for model attribute Asp.Net Core MVC

1 Answered Questions

1 Answered Questions

5 Answered Questions

2 Answered Questions

1 Answered Questions

[SOLVED] Client-side validation for custom StringLength validation attribute

1 Answered Questions

2 Answered Questions

Sponsored Content