I'm having trouble passing the correct data to a partial view, and I'm not sure why it is failing.
Say I have models
public class SubModel {
public string Wobble {get; set;}
}
public class MyModel {
public SubModel Wibble {get; set;}
}
and views
MyView.cshtml
@model MyModel
@Html.Partial("SomePartial", Model.Wibble)
and
SomePartial.cshtml
@model SubModel
<h1>Victory!</h1>
this fails with The model item passed into the dictionary is of type 'MyModel', but this dictionary requires a model item of type 'MySubModel'
When I change MyView.cshtml
to
@model MyModel
@Html.Partial("SomePartial", Model.Wibble, new ViewDataDictionary<MySubModel>(Model.Wibble))
It works as expected.
Why do I need to explicitly pass a ViewDataDictionary
? Why can't I just pass the model?
Note: I'm using a library that does things that make me go hrm? a lot of the time. If the above behaviour is not expected, it might be this libraries fault.
To create a partial view, right click on Shared folder -> select Add -> click on View.. Note: If the partial view will be shared with multiple views, then create it in the Shared folder; otherwise you can create the partial view in the same folder where it is going to be used.
Partial Views can use the Page Model for their data whereas Child Actions use independent data from the Controller. Editor/Display templates pass items from the model to the system but can be overridden by user partial views.
Step 1: Create Models for both Personnel and Professional details. Step 2: Create a regular class file which will act like a DAL, which will supply some data. Step 3: Now Define the Partial Views both for Personnel and Professional details.
This happens when the model you pass to the partial view is null
. Don't pass null to a partial view, or it will get confused about its type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With