RadioButton Helper in MVC3 Razor
- Html.RadioButton is the helper used to render a RadioButton control.
- Helpers are not controls by itself, they simply generate html markup.
- Html.RadioButton is rendered as input type = "radio".
It has following Ovrloads :
Overload 1 :
This overload accepts two parameters i.e. name and value.
Syntax :
<p>
@Html.RadioButton("RadioButton","Hello")
</p>
UI :
Rendered HTML :
<p>
<input id="RadioButton" name="RadioButton" type="radio" value="Hello" />
</p>
This is the HTML that is rendered on the page. The second value parameter is set to value attribute. When the form is posted, this value attribute is used as identifier for radiobutton.
Overload 2 :
This overload accepts three parameter, one more than the previous one i.e. isChecked. This parameter is bool type and decides whether the radiobutton should display as selected or not.
Syntax :
<p>
@Html.RadioButton("RadioButton", "Hello", true)
</p>
UI :
The RadioButton is checked as we have passed isChecked parameter as true.
Rendered HTML :
<p>
<input checked="checked" id="RadioButton" name="RadioButton" type="radio" value="Hello" />
</p>
The checked attribute is set to checked according to the parameter passed.
Overload 3 :
This overload accepts htmlAttributes as the third parameter. The first two parameter being the same as previous overloads.
Syntax :
<p>
@Html.RadioButton("RadioButton", "Hello", new { @class = "radio" })
</p>
UI :
Rendered HTML :
<p>
<input class="radio" id="RadioButton" name="RadioButton" type="radio" value="Hello" />
</p>
We can see the class attribute being set to radio, which is passed as object htmlAttribute.
Overload 4 :
This overload also expects three parameters as previous overload. The third parameter in this case is IDictionary object of htmlAttributes. This object is the collection of attributes to be set.
<p>
@Html.RadioButton("RadioButton", "Hello", radio)
</p>
We have created a Dictionary object and added two attributes to it. This Dictionary object is passed to the above overload.
UI :
Rendered HTML :
<p>
<input class="radio" id="Radiobutton" name="RadioButton" type="radio" value="Hello" />
</p>
The attributes passed as IDictionary object are set as you can see in above section.
Overload 5 :
Syntax :
<p>
@Html.RadioButton("RadioButton", "Hello",true, new {@class = "radio", id="Radiobutton"})
UI :
Rendered HTML :
<p>
<input checked="checked" class="radio" id="Radiobutton" name="RadioButton" type="radio" value="Hello" />
</p>
Overload 6 :
Syntax :
<p>
@Html.RadioButton("RadioButton", "Hello",true, radio)
</p>
UI :
Rendered HTML:
<p>
<input checked="checked" class="radio" id="Radiobutton" name="RadioButton" type="radio" value="Hello" />
</p>
Very Nice. Exactly what I needed.
ReplyDeletesuperb. thanks a lot.
ReplyDelete