2013-05-16 27 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