0

我在Razor視圖中的列表中顯示。其中我有幾個編輯器模板顯示在列表視圖中。這是我的編輯模板。EditorTemplate中的模型活頁夾數據問題

@using Contoso.MvcApplication.Extensions 
@model Contoso.MvcApplication.ViewModels.MultipleChoiceQuestionViewModel 

<h5>@Model.Question.QuestionText</h5> 

<div> 
@Html.RadioButtonForSelectList(m => m.Question.SelectedAnswer, Model.AnswerRadioList) 
@Html.ValidationMessageFor(m => m.Question.SelectedAnswer) 
</div> 

問題是我設置的RadioButtonForSelectList,它結合這樣的話,因爲我知道在這個情況應該是在for循環是這樣的:

@Html.RadioButtonForSelectList(m => m[i].Question.SelectedAnswer, Model.AnswerRadioList) // the index 

但是從編輯模板,我無法知道lambda表達式中的索引。

這是我從複製的HTML擴展的部位:

http://jonlanceley.blogspot.mx/2011/06/mvc3-radiobuttonlist-helper.html

這裏是我使用

public class MultipleChoiceQuestionViewModel 
{ 
    public MultipleChoiceQuestion Question { get; set; } 
    public List<SelectListItem> AnswerRadioList { get; set; } 
} 

如何正確綁定的單選按鈕視圖模型?

當我讀取代碼中的標記時,我列表中的所有模型都具有相同的標識:Question.SelectedAnswer。我認爲這是錯誤的,因爲應該有這樣的索引ID:Question.SelectedAnswer.[INDEX]

UPDATE:

public ActionResult Index(short testId) 
    { 
     GenerateQuiz(testId); 
     StartQuiz(); 

     return View(CreateQuestionViewModel((MultipleChoiceQuestion)CurrentQuestion)); 
    } 

    [HttpPost] 
    public ActionResult Index(MultipleChoiceQuestionViewModel q) 
    { 
     // Save answer state 
     ((MultipleChoiceQuestion)CurrentQuestion).SelectedAnswer = q.Question.SelectedAnswer; 

     if (CurrentNumber == Questions.Count - 1) 
     { 
      QuizCompleted(); 
      return RedirectToAction("ShowResults"); 
     } 
     else 
     { 
      NextQuestion(); 
      return View(CreateQuestionViewModel((MultipleChoiceQuestion)CurrentQuestion)); 
     } 
    } 
+0

所以,你有多個問題,並想添加一個foreach在顯示它們視圖?不知道我是否明白,請你澄清一下嗎? –

+0

最後一個剃鬚刀視圖是EditorTemplate。是的,我有多個問題,我通過我的控制器逐個顯示。讓我更好地向您展示代碼 –

回答

0

認爲顯示的問題應該是這樣的部分:

@for (int j = 0; j < Model.Questions.Count; j++) 
{ 
    <h5> 
     Model.Questions[j].QuestionText 
    </h5> 
    <div> 
     @Html.RadioButtonForSelectList(m => m.Questions[j].SelectedAnswer, Model.AnswerRadioList) 
    </div> 
} 
+0

我也是這樣做的,但我不能這樣做,因爲問題可能有幾個模板(FreeResponse,MultipleChoice,等等。)。這就是我使用EditorTemplates的原因 –