2

私は単純なクイズモデルを持っており、強く型付けされたビューでグループ化された2つのラジオボタンからユーザーが正解/代替回答を選択できるようにしようとしています。しかし、私が使用するラムダ式は機能しません。空のラジオ ボタンが 2 つ表示されます。こことオンラインでいくつかの質問を見てきましたが、私のモデルは 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; }           
    }

私のコントローラー

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

            return View(questions.ToList());

        }

私のモデル:

  @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
        }

}

ありがとうございました

4

1 に答える 1

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; }
}

次に、モデルの要素を単純にループして、目的のマークアップを生成します。

@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>
}

注: フォームが送信されると、POST アクションは、 (プロパティIList<Question>内の) 各質問に対する回答を持つモデルを取ることができます。SelectedAnswer

于 2013-08-01T07:17:55.387 に答える