2011-09-13 21 views
1

我有一個非常簡單的模型奇怪的問題。當回發給控制器時,模型始終爲空。無法找到問題,我把它分開重建模型,一次添加一個訪問器。爲什麼名稱爲「State」的模型訪問器會導致模型發佈爲null?

我終於發現,有一個被稱爲「國家」串訪問和使用它的觀點導致了問題:

<%= Html.HiddenFor(m => m.State) %> 

爲什麼會出現這種情況?

這裏是模型:

public class StudentSelectState 
{ 
    public string State { get; set; } 
    public int SelectedYear { get; set; } 
    public IDictionary<string, string> Years { get; set; } 
} 

這裏是控制器:

[HttpGet] 
    public ActionResult SelectStudent() 
    { 
     var StudentYears = absenceServices.GetStudentYears(); 
     var state = new StudentSelectState {Years = Lists.StudentYearListToDictionary(StudentYears)}; 

     return View(state); 
    } 

    [HttpPost] 
    public ActionResult SelectStudent(StudentSelectState state) 
    { 
     var StudentYears = absenceServices.GetStudentYears(); 

     state.Years = Lists.StudentYearListToDictionary(StudentYears); 

     return View(state); 
    } 

和這裏的觀點:

<% using (Html.BeginForm()) 
    {%> 
    <%= Html.ValidationSummary() %> 
     <%= Html.TextBoxFor(m => m.State) %> 
     <%= Html.RadioButtonListFor(m => m.SelectedYear, Model.Years, "StudentYears") %> 
    <div style="clear: both;"> 
     <input value="submit" /> 
    </div> 
<% } %> 

的RadioButtonListFor是的HtmlHelper我寫來填充RadioButtonLists。

我使用Ninject 2.0將注入服務注入構造函數,但我不認爲這對此問題有影響。

我可以重命名訪問器,但我很好奇爲什麼會發生這種情況。

回答

2

您也可以重命名POST操作的參數。

[HttpPost] 
public ActionResult SelectStudent(StudentSelectState model) 

當您發佈以下是在請求中發送的形式:

State=abcd 

現在默認的模型綁定看到您的操作參數被稱爲狀態並試圖將abcd值綁定它明顯失敗,因爲state變量不是一個字符串。所以在命名視圖模型屬性時要小心。

爲了避免這些衝突,我傾向於命名我的動作參數modelviewModel

然而,如果你不想重命名的任何一種可能是使用[BindPrefix]屬性,就像這樣:

[HttpPost] 
public ActionResult SelectStudent([Bind(Prefix="")]StudentSelectState state) 
0

當StudentSelectState回發給控制器時,默認模式聯編程序(因爲您沒有使用IModelBinder)無法知道何時放入StudentSelectState實例。

該視圖不會保持State屬性的狀態,它必須在表單中指定或從不同的方法獲取以返回到控制器操作。

您可以使用一個隱藏字段或使用自定義IModelBinder類來綁定它。

希望這會有所幫助。

+0

伯尼嗨,如果我改變訪問器名稱的狀態,並用手摸無其他代碼,模型返回填充(助手的radiobuttonlist將SelectedYear設置爲從單選按鈕列表中選擇的選項)。這就是我發佈這個問題的原因。 –

相關問題