Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a model property to a partial view

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.

like image 749
Martijn Avatar asked Apr 10 '14 11:04

Martijn


People also ask

How do you pass model data to partial view?

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.

Can we use model in partial view?

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.

How do you call a partial view from a different model?

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.


1 Answers

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.

like image 132
Martijn Avatar answered Sep 28 '22 06:09

Martijn