Rendering strongly-typed partial view with a different model
I have two views: 1) Register – primary view for creating user account 2) Category – partial view for adding category dynamically if it's not there in a register view combo field.
The Category view is shown as jQuery dialog when user click on Add Category while registering. This view shows fields required to make up a new category like name and description. For this reason, it has a separate model.
On get page everything works fine, however on post, if there's some validation error, the page needs to reload with user provider values for making correction, instead it throws following error:
Exception Details: System.InvalidOperationException: The model item passed into the dictionary is of type 'Delight.Models.User', but this dictionary requires a model item of type 'Delight.Models.Categ开发者_如何学编程ory'.
I thought that using the following statement might be causing this problem (since it doesn't specify the model object to use for partial view):
@Html.Partial("CreateCat")
However, resorting to the following overload didn't solve the problem either:
@Html.Partial("CreateCat", null, null)
Above the second parameter (with null value) represents the model object.
However, unexpectedly following solved my problem:
@Html.Partial("CreateCat", new Category(), null)
Why is empty object working in this case but null isn't?
Is there any other better way to render strongly-typed partial view with different model type.
Unless you want to use the parent's model or no model, you should always pass in the appropriate model for a partial view. Passing in null is silly, if you don't want an instantiated model in your partial view then why would your partial view use a model at all? In this instance, I think new Category() is the correct choice. However, I've always seen sub models passed into partials
@Html.Partial("CreateCat", Model.Category)
something about needing to do what you're doing seems strange, but I'm not certain how you're using the partial view.
精彩评论