Asp.net MVC Razor如何显示两个模型字段的分组单选按钮

iAt*_*_it 2 c# asp.net-mvc razor asp.net-mvc-3 asp.net-mvc-4

我有一个简单的测验模型,我试图让用户从一个强类型视图中分组的两个单选按钮中选择正确答案/替代答案.但我使用的lambda表达式不起作用.我有两个空白的单选按钮.我在这里看过几个问题,在线但我的模型是IList <>,我找不到合适的例子.我找到的所有示例都使用非IList <>.

这是我的模特

模型:

public partial class Question
    {
        public int QuestionID { get; set; }
        public string QuestionBody { get; set; }
        public string CorrectAnswer { get; set; }
        public string AlternativeAnswer { get; set; }           
    }
Run Code Online (Sandbox Code Playgroud)

我的控制器

public ActionResult Index()
        {
            QuizSimpleEntities quizEntities = new QuizSimpleEntities();
            var questions = from p in quizEntities.Questions
                            select p;

            return View(questions.ToList());

        }
Run Code Online (Sandbox Code Playgroud)

我的型号:

  @model IList<Quiz.Models.Question>                                

 <h2>Welcome to the Quiz</h2>
  @Html.BeginForm(method:FormMethod.Post,controllerName:"Home",actionName:"index")
    {
        @foreach (var questions in Model)
        {

        <p>@questions.QuestionBody</p>  

        @* How to display the CorrectAnswer and AlternativeAnswer
           as two radio buttons grouped here? I will be posting the selected value back
        }
Run Code Online (Sandbox Code Playgroud)

}

谢谢

Dar*_*rov 6

您需要在视图模型上拥有一个属性,该属性将在发布表单时保留所选答案:

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; }
}
Run Code Online (Sandbox Code Playgroud)

然后简单地遍历模型的元素并生成所需的标记:

@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>
}
Run Code Online (Sandbox Code Playgroud)

注意:提交表单后,POST操作可以采用一个IList<Question>模型,您将获得每个问题的答案(在SelectedAnswer属性中).