MVC Radio Button Lists are not grouped when using the HtmlHelper class

前端 未结 1 1275
感情败类
感情败类 2021-01-02 16:58

Having trouble creating a list of radio buttons that are grouped together, in MVC 3 specifically, but this also applies to MVC 2.

The problem arises when radio butto

相关标签:
1条回答
  • 2021-01-02 17:08

    You haven't shown how does your view model look like but you could group them by some property. So let's take an example:

    public class MyViewModel
    {
        [Required]
        public string SomeProperty { get; set; }
    }
    

    Controller:

    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View(new MyViewModel());
        }
    
        [HttpPost]
        public ActionResult Index(MyViewModel model)
        {
            return View(model);
        }
    }
    

    View:

    @model AppName.Models.MyViewModel
    @using (Html.BeginForm())
    {
        <div>A: @Html.RadioButtonFor(x => x.SomeProperty, "a")</div>
        <div>B: @Html.RadioButtonFor(x => x.SomeProperty, "b")</div>
        @Html.ValidationMessageFor(x => x.SomeProperty)
        <input type="submit" value="OK" />
    }
    

    Now if you want to preselect some radio simply set the property of the view model to the corresponding value of the radio instead of writing some ugly C# code in your views:

    public ActionResult Index()
    {
        var model = new MyViewModel
        {
            SomeProperty = "a" // select the first radio
        };
        return View(model);
    }
    

    Obviously this technique works with any simple property type (not only strings) and with any number of radio buttons that could be associated to this property.

    0 讨论(0)
提交回复
热议问题