How can i Set RadioButtonFor() as Checked By Default
<%=Html.RadioButtonFor(m => m.Gender,\"Male\")%>
there is way out for (Html.Radio
I found another option so you can just use @Html.EditorFor() with templates:
Say I have this enum:
public enum EmailType { Pdf, Html }
I can put this code in Views/Shared/EditorTemplates/EmailType.cshtml
@model EmailType
@{
var htmlOptions = Model == EmailType.Html ? new { @checked = "checked" } : null;
var pdfOptions = Model == EmailType.Pdf ? new { @checked = "checked" } : null;
}
@Html.RadioButtonFor(x => x, EmailType.Html, htmlOptions) @EmailType.Html.ToString()
@Html.RadioButtonFor(x => x, EmailType.Pdf, pdfOptions) @EmailType.Pdf.ToString()
Now I can simply use this if I want to use it at any time:
@Html.EditorFor(x => x.EmailType)
It's much more universal this way, and easier to change I feel.
<%: Html.RadioButtonFor(m => m.Gender, "Male", new { @checked = true } )%>
or
@checked = checked
if you like
If you're using jquery, you can call this right before your radio buttons.
$('input:radio:first').attr('checked', true);
^ This will check the first radio box, but you can look at more jquery to cycle through to the one you want selected.
This Helper evaluates the expression and if equals to the value it checks the radio button, and has the same parameters than RadioButtonFor (for this reason the name is diferent):
public static MvcHtmlString CheckedRadioButtonFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object value)
{
return CheckedRadioButtonFor(htmlHelper, expression, value, null);
}
public static MvcHtmlString CheckedRadioButtonFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object value, object htmlAttributes)
{
var func = expression.Compile();
var attributes = new RouteValueDictionary(htmlAttributes);
if ((object)func(htmlHelper.ViewData.Model) == value) {
attributes["checked"] = "checked";
}
return htmlHelper.RadioButtonFor(expression, value, attributes);
}
Usage:
<%= Html.CheckedRadioButtonFor(m => m.Gender, "Male", new { id = "gender-male" })%>
Result:
<!-- For Model.Gender = "Male" -->
<input checked="checked" id="gender-male" name="Gender" type="radio" value="Male">
<!-- For Model.Gender = "Female" -->
<input id="gender-male" name="Gender" type="radio" value="Male">
It's not too pretty, but if you have to implement only very few radio buttons for the entire site, something like this might also be an option:
<%=Html.RadioButtonFor(m => m.Gender,"Male",Model.Gender=="Male" ? new { @checked = "checked" } : null)%>
I assume you should have a group of radio buttons. something could be like
<%=Html.RadioButtonFor(m => m.Gender,"Male")%>
<%=Html.RadioButtonFor(m => m.Gender,"Female")%>
<%=Html.RadioButtonFor(m => m.Gender,"Unknown")%>
You may give the default value for m.Gender = "Unknown" (or something) from your controller.