When using .net MVC RadioButtonFor(), how do you group so only one selection can be made?

前端 未结 3 1625
名媛妹妹
名媛妹妹 2020-11-28 09:52

This one has me stumped, I have a strongly typed view that has this loop to generate radiobuttons:

<% foreach (QuestionAnswer qa in Model.QuestionAnswers)         


        
3条回答
  •  离开以前
    2020-11-28 10:28

    In my case, I had a collection of radio buttons that needed to be in a group. I just included a 'Selected' property in the model. Then, in the loop to output the radiobuttons just do...

    @Html.RadioButtonFor(m => Model.Selected, Model.Categories[i].Title)
    

    This way, the name is the same for all radio buttons. When the form is posted, the 'Selected' property is equal to the category title (or id or whatever) and this can be used to update the binding on the relevant radiobutton, like this...

    model.Categories.Find(m => m.Title.Equals(model.Selected)).Selected = true;
    

    May not be the best way, but it does work.

提交回复
热议问题