Sunday, May 4, 2014

How to use Html.Label, Html.Checkbox and Html.RadioButton Html Helpers in ASP.NET MVC


As many ASP.NET MVC Developers already know, you can easily render Views using plain old HTML markup.
Also, you can use model binding and use the corresponding For Html Helpers to output values from the Model.
However, if you just want to learn how to use the Html Helpers, there is no better way to play around with them than just using the Html Helpers without the corresponding For methods.
Of course, getting the CORRECT Html output with the Html Helpers is a bit tricky and is not really well documented on MSDN.
Therefore, here are a few examples to help you get started:
Html.Label Helper method:
@Html.Label("Wednesday", new {@for="Wednesday"})
Html.Checkbox Helper method:

@Html.CheckBox("days", false, new {id="Wednesday", value="Wednesday"})

Html.RadioButton Helper method:


@Html.RadioButton("clubmembership", "IsMember", new {id="IsMember" })



Unfortunately, with the Html.Checkbox Helper method, the Html output rendered is less than ideal:


<input id="Wednesday" name="days" type="checkbox" value="Wednesday" />
<input name="days" type="hidden" value="false" />


As you can see from the above code, an additional Hidden form element is added to the the Checkbox field rather than simply rendering the Checkbox element as it is defined.  I am not exactly sure why the Html.Checkbox Helper method does this while ignoring it for the RadioButton control, but it does not seem to affect the functionality nor rendering of the page in any way since they are hidden controls/hidden form fields.

No comments:

Post a Comment