Asp.net MVC Razor how to show grouped radio buttons for two model fields

前端 未结 1 1537
一整个雨季
一整个雨季 2021-01-15 06:37

I have a simple quiz model, and I am trying to let the user select Correct Answer/Alternative answer from two radio buttons, grouped , in a strongly typed view. But the lamb

1条回答
  •  臣服心动
    2021-01-15 07:19

    You need to have a property on your view model that will hold the selected answer when the form is posted:

    public partial class Question
    {
        public int QuestionID { get; set; }
        public string QuestionBody { get; set; }
        public string CorrectAnswer { get; set; }
        public string AlternativeAnswer { get; set; }           
    
        public string SelectedAnswer { get; set; }
    }
    

    and then simply loop through the elements of your model and generated the desired markup:

    @model IList                                
    
    

    Welcome to the Quiz

    @Html.BeginForm( method:FormMethod.Post, controllerName:"Home", actionName:"index") { @for (var i = 0; i < Model.Count; i++) { @Html.HiddenFor(x => x[i].QuestionID)
    @Html.DisplayFor(x => x[i].QuestionBody)
    • @Html.HiddenFor(x => x[i].CorrectAnswer) @Html.RadioButtonFor(x => x[i].SelectedAnswer, Model[i].CorrectAnswer) @Html.DisplayFor(x => x[i].CorrectAnswer)
    • @Html.HiddenFor(x => x[i].AlternativeAnswer) @Html.RadioButtonFor(x => x[i].SelectedAnswer, Model[i].AlternativeAnswer) @Html.DisplayFor(x => x[i].AlternativeAnswer)
    } }

    NOTE: When the form is submitted the POST action could take an IList model where you will have the answers for each question (in the SelectedAnswer property).

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