I have seen a few threads on this but none seem to apply to MVC4 because the RadioButtonFor html extension method/helper does not exist.
Say I have an enum list - i.e Airlines:
public enum Airlines { Unknown = 0, BritishAirways = 1, VirginAtlantic = 2, AirFrance = 3 }
How can I bind this to a Radio button list on my view and be able to retrieve the selected item? What about being able to say "select one item" if there is no selection made?
You can create a custom Editor Template for the enum Airlines
that will render a radio button list. In your Model you will have a property of type Airlines
and tag this property with the Required
attribute and set ErrorMessage = "select one item"
. Don't forget to include the jQuery validation for client side validation if you want it, usually just have to add @Scripts.Render("~/bundles/jqueryval")
on your Layout or View. If you don't use the jQuery validation you will need to make the property nullable on the model because enums are just set to the first value by default so MVC will not see it as invalid. Remember if you change the property to nullable you will also need to change the Model type of your Editor Template to nullable as well.
UPDATE
To enable the Editor Template to render a radio button list for any enum, change the template to the following:
@model Enum @foreach (var value in Enum.GetValues(Model.GetType())) { @Html.RadioButtonFor(m => m, value) @Html.Label(value.ToString()) }
ORIGINAL
The Editor Template, Airlines.cshtml, in the Views\Shared\EditorTemplates directory:
@model MvcTest.Models.Airlines @foreach (var value in Enum.GetValues(typeof(MvcTest.Models.Airlines))) { @Html.RadioButtonFor(m => m, value) @Html.Label(value.ToString()) }
The Model:
public class TestModel { [Required(ErrorMessage = "select one item")] public Airlines Airline { get; set; } }
The action methods:
public class HomeController : Controller { [HttpGet] public ActionResult Index() { return View(new TestModel()); } [HttpPost] public ActionResult Index(TestModel model) { if (ModelState.IsValid) { return RedirectToAction("Index"); } return View(model); } }
The view:
@model MvcTest.Models.TestModel @{ ViewBag.Title = "Index"; Layout = "~/Views/Shared/_Layout.cshtml"; } <h2>Index</h2> @using (Html.BeginForm()) { @Html.EditorFor(m => m.Airline) <input type="submit" value="Submit" /> @Html.ValidationSummary(false) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With