Multiple radio button groups in MVC 4 Razor

后端 未结 5 1688
耶瑟儿~
耶瑟儿~ 2020-12-03 06:33

I need to have multiple radio button groups in my form like this:
\"enter

I know

5条回答
  •  不思量自难忘°
    2020-12-03 07:22

    I fixed a similar issue building a RadioButtonFor with pairs of text/value from a SelectList. I used a ViewBag to send the SelectList to the View, but you can use data from model too. My web application is a Blog and I have to build a RadioButton with some types of articles when he is writing a new post.

    The code below was simplyfied.

    List items = new List();
    
    Dictionary dictionary = new Dictionary();
    
    dictionary.Add("Texto", "1");
    dictionary.Add("Foto", "2");
    dictionary.Add("Vídeo", "3");
    
    foreach (KeyValuePair pair in objBLL.GetTiposPost())
    {
        items.Add(new SelectListItem() { Text = pair.Key, Value = pair.Value, Selected = false });
    }
    
    ViewBag.TiposPost = new SelectList(items, "Value", "Text");
    

    In the View, I used a foreach to build a radiobutton.

    @foreach (var item in (SelectList)ViewBag.TiposPost) { @Html.RadioButtonFor(model => model.IDTipoPost, item.Value, false) }

    Notice that I used RadioButtonFor in order to catch the option value selected by user, in the Controler, after submit the form. I also had to put the item.Text outside the RadioButtonFor in order to show the text options.

    Hope it's useful!

提交回复
热议问题