I have a model A which has a property which is of another model type, B. I have a view which is tied to A. I want to add a partial view to to A which takes a model of type B. This is my code
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'
The line works if i change it to @Html.Partial("FileLinks", new ModelB())
Why doesn't the original code work? The property is of type ModelB.
Any help is appreciated thanks!
Update: I forgot to add some code from the Controller
m.FileLinks = new ModelB() return View("Index", m)
So the model is not null
what i think happening here is that
when you render a partial view like this the ViewDataDictionary
and the Views Context is passed to the partial view
so when the ModelB
is null then the ViewDataDictionary<TModel>
isnt changed and at runtime teh MVC engine cannot determine the type of model from a null
value.