How to call a partial view with a null value for its model?

Suppose I have a partial view called UserDetails , whose @model installed in 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 the view for SpecialModel , I want to call my partial view, mentioned above:

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

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

System.InvalidOperationException : the model element passed to the dictionary is of type "MyProject.Models.SpecialModel", but this dictionary requires a model element of type "MyProject.Models.User".

Clearly the message of the exception lies. How to fix this correctly so that I can pass null normally?

+7
source share
1 answer

Instead

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

write more detailed

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

This makes this particular scenario work.

However, it has a drawback: it clears all the information transmitted from the controller. In particular, it clears all validation information; if you send some data and want to display a validation error message in this partial view, you cannot use this technique.

+18
source

All Articles