2013-08-01 69 views
2

我有一個簡單的測驗模型,我試圖讓用戶從兩個單選按鈕,選擇正確答案/備選答案,分組,在一個強類型視圖。但是我使用的lambda表達式不起作用。我得到兩個空白的單選按鈕。我在這裏查看了幾個問題,在線但我的模型是IList <>,我找不到合適的示例。我找到的所有例子都與非IList <>合作。Asp.net MVC剃刀如何顯示歸類單選按鈕有兩個示範田

這是我的模型

型號:

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 
     } 

}

謝謝

回答

5

您必須對您的視圖模型物業時的形式發佈,將舉行所選答案:

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屬性)。

+0

大。你回答了這兩個問題......這將做到!謝謝!!!!!! –

+0

我不明白爲每個單選按鈕添加的隱藏字段的用途。這是記錄在任何地方? –