10

Suppose I have a partial view called UserDetails whose @model clause is set to a model class called User.

Now suppose I have another model class that looks something like this:

public sealed class SpecialModel
{
    public User SpecialUser;
    public ... // other stuff
}

Inside a view for the SpecialModel, I want to invoke my partial view mentioned above:

@model MyProject.Models.SpecialModel
@{ ViewBag.Title = "..."; }
<div class='user'>@Html.Partial("UserDetails", Model.SpecialUser)</div>

This works just fine if the user is not null. However, if the user is null, I get this exception:

System.InvalidOperationException: The model item passed into the dictionary is of type 'MyProject.Models.SpecialModel', but this dictionary requires a model item of type 'MyProject.Models.User'.

Clearly, the exception message is lying. How do I fix this properly so that I can pass null normally?

Timwi
  • 65,159
  • 33
  • 165
  • 230

1 Answers1

19

Instead of

@Html.Partial("UserDetails", Model.SpecialUser)

write the more verbose

@Html.Partial("UserDetails", new ViewDataDictionary(Model.SpecialUser))

That makes this specific scenario work.

However, it has a downside: it clears all information passed from the controller. In particular, it clears all the validation information; if you are posting some data and you want to display a validation error message inside that partial view, you can’t use this technique.

Timwi
  • 65,159
  • 33
  • 165
  • 230
  • The following solution [here](http://stackoverflow.com/a/12037580/649497) overcomes the downside! – Mojtaba Jun 01 '16 at 16:24
  • This no longer works for dotnet core 2 / mvc 2.0.3. [But I've found a solution that does.](https://stackoverflow.com/questions/650393/renderpartial-with-null-model-gets-passed-the-wrong-type#comment85738016_713921) – Jay Mar 19 '18 at 17:37
  • Yea, it clears away all the validation information and your ViewBag. "Other than that, how did you like the play, Mrs. Lincoln?" – Tom Baxter Jun 18 '18 at 02:08