2013-07-12 184 views
0

一個控制器方法,我有被聲明爲「調查」頁面如下:傳遞數據通過POST

@using (Html.BeginForm("Survey", "Home", new { questionList = Model.Questions }, FormMethod.Post)) 
{ 
    <div class="survey"> 
     <ol class="questions"> 
      @foreach (Question q in Model.Questions) 
      { 
       <li class="question" id="@q.QuestionName"> 
        @q.QuestionText<br /> 
        @foreach (Answer a in q.Answers) 
        { 
         <input class="answer" id="@a.DisplayName" type="checkbox" /><label for="@a.DisplayName">@a.AnswerText</label> 
         if (a.Expandable) 
         { 
         <input type="text" id="@a.DisplayNameFreeEntry" maxlength="250" /> <span>(250 characters max)</span> 
         } 
         <br /> 
        } 
       </li> 
      } 
     </ol> 
    </div> 
    <div class="buttons"> 
     <input type="submit" value="Finish" /> 
    </div> 
} 

當我逐句通過我的代碼,它擊中我設置的方法處理他們的調查結果顯示:

[HttpPost] 
public ActionResult Survey(List<Question> questionList, FormCollection postData) 
{ 
    //Process Survey 
} 

然而,當我通過我發現這個變量questionList步驟爲空並且變量postData不從表格包含任何數據。試圖通過Request[a.Displayname訪問複選框也不起作用。

我讀過的一切都表明,這是將模型中的值保存到提交方法的正確方法,並且我應該能夠以這種方式訪問​​FormCollection。

我在做什麼錯?

+0

你可能會看到這個http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx和這個http://stackoverflow.com/questions/5496593/mvc- net-model-binding-to-the-on-the-fly/5499341#5499341 – Tassadaque

回答

1

您必須將questionList另存爲頁面上的隱藏字段。非基本類型不要被路過他們只是堅持着。

你能做到這一點

一種方法是

@Html.HiddenFor(m => m.Foo) 

或者你可以直接做在HTML這樣

<input type="hidden" name="Var" value="foo"> 

哪裏m是你的模型。

+0

我很新MVC的顯示方面。如何將questionList保存爲隱藏字段? – Jeff

0

一個問題是您的複選框和您的文本框沒有正確綁定到您的模型。

您應該使用@Html.CheckBoxFor@Html.TextBoxFor

1

的事實postData是空的是奇怪的,因爲一個表單標籤內的ID爲每個輸入元素應該用POST請求傳遞。

但是questionList將不會以這種方式接收,因爲它是一個複雜類的列表(不僅僅是一個字符串或int),而且默認爲ModelBinder(將HTTP請求變量轉換爲參數傳遞給動作的東西方法)不支持複雜類的列表。

如果你想能夠接收列表,你將不得不實現自己的綁定機制與CustomModelBinder

This article可以幫助你實現它。