2013-05-16 25 views
4

我有一個模型A有一個屬性是另一種模型類型,B.我有一個視圖是綁定到A.我想添加一個局部視圖到A,它需要B型的模型這是我的代碼部分視圖模型不能解決

public class ModelA 
{ 
    public bool Prop1 {get;set;} 
    public bool Prop2 {get; set;} 
    public Dictionary<int, string> Prop3{get; set;} 
    public int Prop4 {get; set;} 
    public ModelB Prop5 { get; set; } 


    public ModelA() 
    { 
     Prop5 = null; 

     ... more code ... 
    } 
} 

//This view is tied to ModelA 
@using (Html.BeginForm("CreateReport", "Home", FormMethod.Post)) 
{ 
    some markup 
} 

//this is the problem 
@Html.Partial("FileLinks", Model.Prop5) //This line throws an error 

Error: The model item passed into the dictionary is of type 'ModelA', but this dictionary requires a model item of type 'ModelB'

線工作,如果我將其更改爲@Html.Partial("FileLinks", new ModelB())

爲什麼沒有原代碼的工作?該物業屬於ModelB型。

任何幫助表示讚賞謝謝!

更新:我忘了從控制器中添加一些代碼

m.FileLinks =新ModelB() 返回查看( 「指數」,M)

因此模型不爲空

+0

發佈FileLinks查看請? – Fals

回答

0

什麼,我認爲在這裏發生的是,

當你渲染這樣的ViewDataDictionary和查看上下文傳遞給局部視圖
所以ModelB時的局部視圖爲空,那麼ViewDataDictionary<TModel>未被更改,並且在運行時,MVC引擎無法通過null值確定模型的類型。

+0

這是有道理的。我忘了添加其他的東西,在上面的控制器操作中,我初始化FileLinks initalize,就像FileLinks = new ModelB()那樣返回帶有該模型的視圖。當視圖返回時,prop5不再爲null。代碼:m.FileLines = new ModelB(); return View(「Index」,m) –

+0

我確實認爲這是答案。 –

4

我剛試過這個,如果Prop5爲空,我會得到相同的錯誤。如果我將Prop5初始化爲新的ModelB,那麼它就可以工作。

錯誤不是很清楚(你會認爲這會拋出一個NullReferenceException)。

我也試過這樣:

@Html.Parial("FileLinks",null) 

,並出現相同的錯誤。這似乎是同樣的問題,因爲this

+0

+1你釘了它,這是同樣的問題。 – rsenna