How to Set RadioButtonFor() in ASp.net MVC 2 as Checked by default
Asked Answered
B

14

44

How can i Set RadioButtonFor() as Checked By Default

<%=Html.RadioButtonFor(m => m.Gender,"Male")%>

there is way out for (Html.RadioButton) but not for (Html.RadioButtonFor)

any Ideas?

Bartholomew answered 8/4, 2010 at 9:7 Comment(1)
Is there no option for By default Check when using RadioButtonFor()Bartholomew
I
12

This question on StackOverflow deals with RadioButtonListFor and the answer addresses your question too. You can set the selected property in the RadioButtonListViewModel.

Inadvertency answered 11/4, 2010 at 21:38 Comment(0)
P
85

Use the simple way:

<%= Html.RadioButtonFor(m => m.Gender, "Male", new { Checked = "checked" })%>
Pinup answered 27/8, 2010 at 16:46 Comment(2)
Thanks! Can also be new { @checked = "checked" }.Messick
Can I bind Checked property here to Boolean property of a model? such that when i click on it the boolean property turns to true and i can bind that true value to a action method?Chauffer
R
16

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

Reprobate answered 24/8, 2010 at 15:12 Comment(0)
C
14

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.

Chalaza answered 9/4, 2010 at 13:42 Comment(2)
But i want only two radiobutton with one of them checked bydefault using Html.RadiobuttonFor()Bartholomew
I struggled with this as well, but found this answer is so simple. If you create a property on your model, let's say Gender, in your model's default constructor, just set that property to the default gender, like Gender = "Male";. If you do this, mvc.net will automatically select the default and on postback will automatically bind the selected value to your Gender property.Boutte
I
12

This question on StackOverflow deals with RadioButtonListFor and the answer addresses your question too. You can set the selected property in the RadioButtonListViewModel.

Inadvertency answered 11/4, 2010 at 21:38 Comment(0)
B
8

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">
Bilestone answered 24/9, 2010 at 0:9 Comment(1)
You should use the HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes); instead of the new RouteValueDictionary(htmlAttributes) in order to not lose the automatic convertsion of the data_something to data-somethingHarriot
J
3

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.

Juliannajulianne answered 3/6, 2011 at 4:2 Comment(0)
M
3

Came across this and thought I would point out that for MVC 5 all you need to do is set the value on the model. For Example:

Model:

   public class ExampleModel
    {
        public PackingListInputModel()
        {

             RadioButtonField = "One";

        }
        public string RadioButtonField { get; set; }
    }

View :

@model ExampleModel

@using (Html.BeginForm)
{
    @Html.RadioButtonFor(m => m.RadioButtonField , "One")
    @Html.RadioButtonFor(m => m.RadioButtonField , "Two")
}

The state of the first radio button ("One") will be set as active because the value matches what was set in the model.

Mclaurin answered 1/4, 2019 at 9:27 Comment(0)
S
2

You can also add labels that are tied to your radio buttons with the same ID, which then allows the user to click the radio button or label to select that item. I'm using constants here for "Male", "Female" and "Unknown", but obviously these could be strings in your model.

<%: Html.RadioButtonFor(m => m.Gender, "Male", 
    new Dictionary<string, object> { { "checked", "checked" }, { "id", "Male" } }) %>
<%: Html.Label("Male") %>

<%: Html.RadioButtonFor(m => m.Gender, "Female", 
    new Dictionary<string, object> { { "id", "Female" } }) %>
<%: Html.Label("Female")%>

<%: Html.RadioButtonFor(m => m.Gender, "Unknown",
    new Dictionary<string, object> { { "id", "Unknown" } }) %>
<%: Html.Label("Unknown")%>
Sardanapalus answered 3/10, 2010 at 20:23 Comment(1)
Thanks! was having difficulty in creating the label for the checkbox. Quite obvious now, but could not figure out!Remonaremonetize
W
1
<%: Html.RadioButtonFor(m => m.Gender, "Male", new { @checked = true } )%>

or

@checked = checked

if you like

Warrick answered 13/10, 2010 at 20:10 Comment(0)
F
0

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.

Fy answered 20/5, 2010 at 19:57 Comment(0)
A
0
           @Html.RadioButton("Insured.GenderType", 1, (Model.Insured.GenderType == 1 ))
           @Web.Mvc.Claims.Resources.PartyResource.MaleLabel
           @Html.RadioButton("Insured.GenderType", 2, Model.Insured.GenderType == 2)
           @Web.Mvc.Claims.Resources.PartyResource.FemaleLabel
Axolotl answered 5/11, 2011 at 15:3 Comment(0)
T
0

Here is code to set default radio button set to true

@Html.RadioButtonFor(m => m.Gender, "Male", new { @checked = "checked", id = "rdGender", name = "rbGender" })
Teletypewriter answered 1/10, 2015 at 10:28 Comment(0)
F
0

I find it best to just put the default value in the constructor method of the model.

Gender = "Male";
Father answered 15/9, 2016 at 15:14 Comment(0)
A
-1

You need to add 'checked' htmlAttribute in RadioButtonFor, if the radiobutton's value matches with Model.Gender value.

@{
        foreach (var item in Model.GenderList)
        {
            <div class="btn-group" role="group">
               <label class="btn btn-default">
                   @Html.RadioButtonFor(m => m.Gender, item.Key, (int)Model.Gender==item.Key ? new { @checked = "checked" } : null)
                   @item.Value
              </label>
            </div>
        }
    }

For complete code see below link: To render bootstrap radio button group with default checked. stackoverflow answer link

Arlberg answered 26/10, 2016 at 15:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.