Strongly Typed RadioButtonlist

Vivek picture Vivek · Apr 14, 2011 · Viewed 22.9k times · Source

I want to get some options (say payment method cash, credit card etc.) and bind these to radio buttons. I believe there is no RadioButtonList in MVC 3.

Also, once radios are bound I want to show the previously selected option to the user while editing the answer.

Answer

Darin Dimitrov picture Darin Dimitrov · Apr 14, 2011

As always you start with a model:

public enum PaiementMethod
{
    Cash,
    CreditCard,
}

public class MyViewModel
{
    public PaiementMethod PaiementMethod { get; set; }
}

then a controller:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var model = new MyViewModel();
        return View(model);
    }

    [HttpPost]
    public ActionResult Index(MyViewModel model)
    {
        return View(model);
    }
}

and finally a view:

@model MyViewModel
@using (Html.BeginForm())
{
    <label for="paiement_cash">Cash</label>
    @Html.RadioButtonFor(x => x.PaiementMethod, "Cash", new { id = "paiement_cash" })

    <label for="paiement_cc">Credit card</label>
    @Html.RadioButtonFor(x => x.PaiementMethod, "CreditCard", new { id = "paiement_cc" })

    <input type="submit" value="OK" />
}

And if you want some more generic solution which encapsulates this in a helper you may find the following answer helpful.