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

前端 未结 1 1893
清歌不尽
清歌不尽 2021-01-15 06:36

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:28

    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<Quiz.Models.Question>                                
    
    <h2>Welcome to the Quiz</h2>
    @Html.BeginForm( method:FormMethod.Post, controllerName:"Home", actionName:"index")
    {
        @for (var i = 0; i < Model.Count; i++)
        {
            @Html.HiddenFor(x => x[i].QuestionID)
            <fieldset>
                <legend>
                    @Html.DisplayFor(x => x[i].QuestionBody)
                </legend>
                <ul>
                    <li>
                        @Html.HiddenFor(x => x[i].CorrectAnswer)
                        @Html.RadioButtonFor(x => x[i].SelectedAnswer, Model[i].CorrectAnswer)
                        @Html.DisplayFor(x => x[i].CorrectAnswer)
                    </li>
                    <li>
                        @Html.HiddenFor(x => x[i].AlternativeAnswer)
                        @Html.RadioButtonFor(x => x[i].SelectedAnswer, Model[i].AlternativeAnswer)
                        @Html.DisplayFor(x => x[i].AlternativeAnswer)
                    </li>
                </ul>
            </fieldset>
        }
    
        <button type="submit">OK</button>
    }
    

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

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