2013-08-01 36 views
0

我有一個「Embedded Resource」視圖。在這種觀點我使用下面的模型在「Embedded Resource」視圖中使用「Content」視圖作爲EditorFor模板

public class TestModel 
{ 
    public TestModel() 
    { 
     CustomModel1 = new CustomModel1(); 
     CustomModel2 = new CustomModel2(); 
    } 

    public CustomModel1 CustomModel1 { get; set; } 

    public CustomModel2 CustomModel2{ get; set; } 
} 

在該視圖中我有一個表格和裏面我使用@Html.EditorFor代替@Html.Partial,因爲當我使用@Html.Partial的CustomModel1傳遞到操作(當窗體提交)是空的。

@Html.EditorFor(m => m.CustomModel1, Constants.CustomEmbeddedView1) 

然而,當我使用@Html.EditorFor,並通過爲模板的「內容」視圖

@Html.EditorFor(m => m.CustomModel1, "~/Views/Common/_CustomPartialView.cshtml") 

我收到以下錯誤:

The model item passed into the dictionary is null, but this dictionary requires a non-null model item of type 'System.Int32'.

如果我設置的「內容」視圖成爲「嵌入式資源」,一切正常。

有什麼辦法可以解決這個問題嗎?也許有另一種解決方案來解決模型綁定問題,而不是使用@Html.EditorFor

回答

1

我找到了解決我的問題的方法。我仍然不知道爲什麼會拋出錯誤,但至少我修復了模型綁定。

與模型結合的問題是,當調用@Html.Partial

@Html.Partial("~/Views/Common/_CustomPartialView.cshtml", Model.CustomModel1) 

被dispayed元素(I使用@Html.EditorFor(m => m.Name)例如在局部視圖)具有id="Name"。因此,模型綁定嘗試在TestModel內查找「名稱」屬性,但名稱屬性位於CustomModel1屬性內。這就是模型綁定不起作用的原因,並且在提交表單時Name屬性是一個空字符串。

解決的辦法是設置HtmlFieldPrefix。

var dataDictCustomModel1 = new ViewDataDictionary { TemplateInfo = { HtmlFieldPrefix = "CustomModel1" } }; 
@Html.Partial("~/Views/Common/_CustomPartialView.cshtml", Model.CustomModel1, dataDictCustomModel1) 

這樣Name屬性的標識符成爲id="CustomModel1_Name",從而使模型綁定正確設置的名稱屬性的值。

這可能有更好的解決方案,但到目前爲止,這是最好的,我已經想出了。

相關問題