Partial view model does not allow

I have a model A that has the property of another type of model B. I have a view that is attached to A. I want to add a partial view 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 element passed to the dictionary is of type "ModelA", but this dictionary requires a model element of type "ModelB"

The line works if I change it to @Html.Partial("FileLinks", new ModelB())

Why is the source code not working? The property is of type ModelB.

Any help is appreciated!

Update: I forgot to add code from the controller

m.FileLinks = new ModelB () return View ("Index", m)

So the model is not null

+4
source share
2 answers

what i think is happening here that

when you present a partial view like this ViewDataDictionary and the view context is passed to the partial view
therefore, when ModelB is null, the ViewDataDictionary<TModel> does not change and at run time, the MVC engine cannot determine the type of model from null .

0
source

I just tried this and I get the same error if Prop5 is null. If I initialize Prop5 in the new ModelB, it will work.

The error is not very clear (you think this will 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

+4
source

Source: https://habr.com/ru/post/1481224/


All Articles