Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default selection in RadioButtonFor

I am generating the radiobutton list and then trying to select one option on load as below.

Foreach loop in View

@foreach (var myListItem in Model.MyList)
 {
    @Html.RadioButtonFor(m => m.MyType,myListItem.MyType, new {id = myListItem.MyType, @Checked = (Model.MyTypeId == myListItem.MyTypeId) })
    @myListItem.MyType
 }

Eventhough the HTML is generated correctly(refer below). The second option is checked instead of 1st even when Model.MyTypeId = 0.

Generated HTML for view

<input id="0" name="MyType" value="Option One" CHECKED="True" type="radio">Option One
<input id="1" name="MyType" value="Option Two  " CHECKED="False" type="radio">Option Two    

Please suggest how else I can select the desired radio button option by deafult.

like image 347
San Avatar asked Mar 24 '23 04:03

San


2 Answers

The HTML isn't correct actually. You need to do something more along these lines:

@foreach (var myListItem in Model.MyList)
{
    if (Model.MyTypeId == myListItem.MyTypeId)
    {
        @Html.RadioButtonFor(m => m.MyType,myListItem.MyType,
            new
            {
                id = myListItem.MyType,
                @Checked = ""
            })
    }
    else
    {
        @Html.RadioButtonFor(m => m.MyType,myListItem.MyType,
            new
            {
                id = myListItem.MyType,
            })
    }
    @myListItem.MyType
}

Though I can't verify the exact output, it should look something like this:

<input id="0" name="MyType" value="Option One" CHECKED type="radio">

You may have to use null to get it to generate the CHECKED without the ="", but that would be okay too. See, it's not the value that's recognized, it's the attribute itself, so that's why the second one is checked.

like image 136
Mike Perrenoud Avatar answered Apr 05 '23 14:04

Mike Perrenoud


Anytime I need a list of radio buttons created from a query, I always reach for this RadioButtonListFor extension method. Works like a charm:

// jonlanceley.blogspot.com/2011/06/mvc3-radiobuttonlist-helper.html
public static MvcHtmlString RadioButtonListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper,
    Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> listOfValues)
{
    var metaData = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
    var sb = new StringBuilder();
    sb.Append("<span class='RadioButtonListFor'> ");

    if (listOfValues != null)
    {
        // Create a radio button for each item in the list
        foreach (SelectListItem item in listOfValues)
        {
            // Generate an id to be given to the radio button field
            var id = string.Format("{0}_{1}", metaData.PropertyName, item.Value);

            // Create and populate a radio button using the existing html helpers

            var htmlAttributes = new Dictionary<string, object>();
            htmlAttributes.Add("id", id);

            if (item.Selected)
                htmlAttributes.Add("checked", "checked");

            var radio = htmlHelper.RadioButtonFor(expression, item.Value, htmlAttributes);


            // Create the html string that will be returned to the client
            // e.g. <label<input data-val="true" data-val-required="You must select an option" id="TestRadio_1" name="TestRadio" type="radio" value="1" />Line1</label>
            sb.AppendFormat("<label>{0} {1}</label> ", radio, HttpUtility.HtmlEncode(item.Text));
        }
    }

    sb.Append(" </span>");
    return MvcHtmlString.Create(sb.ToString());
}

Now, you can generate your Radio Buttons from any collection you have in memory, usually as a property on your ViewModel like this:

public int SelectedPaymentMethodId { get; set; }

public IEnumerable<SelectListItem> PaymentMethodChoices 
{
     get 
     {
          return from x in dataSourceFoo
                 select new SelectListItem { 
                      Text = x.TextThing, Value = x.Id, Selected = (x.Id == SelectedPaymentMethodId) 
                  };
     }
}

And your View is as simple as:

@Html.RadioButtonListFor(model => model.SelectedPaymentMethodId, Model.PaymentMethodChoices)
like image 37
Graham Avatar answered Apr 05 '23 12:04

Graham