2013-09-28 147 views
2

我有以下用於測驗的模型,我試圖提交表單並將現有模型傳遞迴Action,因爲它已在Index操作中初始化。表單提交後保留模型

public class QuizModel 
{ 
    private List<string> _Responses; 

    public List<string> Responses 
    { 
     get 
     { 
      if (_Responses == null) 
      { 
       _Responses = new List<string>() { "Response A", "Response B", "Response C", "Response D" }; 
      } 
      return _Responses; 
     } 
    } 

    public int? SelectedIndex { get; set; } 

    public string Question { get; set; } 
} 

通過以下幾種觀點:

<div class="title">Question</div> 
<span id="question">@Model.Question</span> 
@if (!Model.UserHasAnswered) 
{ 
using (Html.BeginForm("Submit", "Quiz", FormMethod.Post)) 
{ 
    for (int i = 0; i < Model.Responses.Count; i++) 
    { 
     <div class="reponse">@Html.RadioButtonFor(m => m.SelectedIndex, i)@Model.Responses[i]</div> 
    } 
    <input type="submit" value="This is the value" />        
} 
} 
else 
{ 
    <div id="explanation">@Model.Explanation</div> 
} 

和控制器......

// 
    // GET: /Quiz/ 

    public ActionResult Index() 
    { 
     QuizModel model = new QuizModel() 
     { 
      Question = "This is the question", 
      Explanation = "This is the explanation", 
      UserHasAnswered = false 
     }; 

     return PartialView(model); 
    } 

    // 
    // POST: /Quiz/Submit 
    [HttpPost] 
    public ActionResult Submit(QuizModel model) 
    { 
     if (ModelState.IsValid) 
     { 
      int? selected = model.SelectedIndex; 

      model.UserHasAnswered = true; 
     } 

     return View("Index", model); 
    } 

當模型來提交行動它只包含SelectedIndex的,而不是問題或解釋性質。我如何告訴我的觀點將它收到的原始模型傳遞迴提交操作?

回答

3

當您第一次顯示索引時,您的問題和解釋將正確顯示。 然後您提交表單,並且問題和解釋不會將其添加到控制器操作中。

這是因爲您的FORM沒有包含問題和解釋的輸入字段。

添加到您的形式:

@Html.HiddenFor(x => x.Question) 
@Html.HiddenFor(x => x.Explanation) 

如果解釋爲可編輯的用戶,而不是添加一個隱藏了它這樣做:

@Html.TextAreaFor(x => x.Explanation) 

記住:所有的信息你需要發送到您的控制器需要輸入您的FORM內。

這樣,你的視圖將成爲:

<div class="title">Question</div> 
<span id="question">@Model.Question</span> 
@if (!Model.UserHasAnswered) 
{ 
using (Html.BeginForm("Submit", "Quiz", FormMethod.Post)) 
{ 
    @Html.HiddenFor(x => x.Question) 
    @Html.HiddenFor(x => x.Explanation) 
    for (int i = 0; i < Model.Responses.Count; i++) 
    { 
     <div class="reponse">@Html.RadioButtonFor(m => m.SelectedIndex, i)@Model.Responses[i]</div> 
    } 
    <input type="submit" value="This is the value" />        
} 
} 
else 
{ 
    <div id="explanation">@Model.Explanation</div> 
} 
0

我相信你index動作要象下面這樣的情景:

public ActionResult Index(QuizModel model) 
{ 
    if(model == null) 
    { 
     model = new QuizModel() 
     { 
      Question = "This is the question", 
      Explanation = "This is the explanation", 
      UserHasAnswered = false 
     }; 
    } 

    return PartialView(model); 
} 

希望這將幫助!

+0

仍然沒有能夠從提交行動訪問相同的模型。當表單發佈到「提交」操作時,我希望它獲得與「索引」操作中初始化的相同模型。 – jimmyjambles

+0

@jimmyjambles,請在您的提交操作中檢查您的模型。 –

+0

我是模型進來只有selectedIndex屬性填充和問題和解釋屬性爲空 – jimmyjambles