4

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

2 Answers2

4

I just tried this and I get the same error if Prop5 is null. If I initialize Prop5 to a new ModelB then it works.

The error is not very clear (you would think this would throw a NullReferenceException).

I also tried this:

@Html.Parial("FileLinks",null)

and the same error occurs. This seems to be the same issue as this

Community
  • 1
  • 1
HitLikeAHammer
  • 2,679
  • 3
  • 37
  • 53
0

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.

Parv Sharma
  • 12,581
  • 4
  • 48
  • 80
  • This makes sense. I forgot to add something else , in the controller action above, i initialize initalize FileLinks like so FileLinks = new ModelB() then return the view with that model.Sp prop5 is no longer null when the view is returned. Code: m.FileLines = new ModelB(); return View("Index", m) – Debbra Sparks May 16 '13 at 18:38
  • I do think this is the answer. – Debbra Sparks May 17 '13 at 11:42