1
votes

I've a problem with Partial View. I am developing a blog in asp.net mvc and I would make in my masterpage a list of categories, last post, last comments. I think that the best solution is to use strongly typed partial view, and in each partial view pass the necessary model.

MY problem is that the model in View.. in any view (connected to the masterpage's contentplaceholder) enter in conflict with the models in partial views and I get an error like this:

The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[Blog.Models.Articoli]' but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[Blog.Models.Categorie]'. 

I found on web a dirty solution that consist of to pass togheter the model of any view, some viewdata, one for every model to pass in partial view. But this solution don't respect DRY Principle..because you must repeat this code for each action!

So, my question is: Can I create a model that contain also partial view's model? If, yes, in that way?

It Exist another solution more simple?

Thanks for help

2
I've run into this before. Post the header of your View and the RenderPartialView code, pleasehunter

2 Answers

5
votes

How about the View Model Pattern?

I've created wrapper classes that are passed to my views rather than whatever object I would normally use

public class MyCreateUserView
{
    public User CreatingUser { get; set; }
    public MyPartialViewObject Blah { get; set; }
}

In your view write:

public ActionResult CreateUser()
{
    MyCreateUserView createUser = new MyCreateUserView()
    {
        CreatingUser = GetUserFromSomewhere(),
        Blah = GetPartialViewObject();
    }

    return View(createUser);
}

Then your page header looks like so:

<%@ Page Language="C#" Inherits="ViewPage<MyCreateUserView>" %>

and when you render your partial write:

<% Html.RenderPartial("../MyPartialViewObject ", Model.Blah); %>
1
votes

Instead of solving that with the pattern you describe (which is generally a great pattern), I solve that with calls to RenderAction and have it return a partial view. That way the code is in one place as each call to each view does not have to worry about marshalling all the data you need. If you want to see a short discussion on how to use it, I would check Haack's blog here: http://haacked.com/archive/2009/11/18/aspnetmvc2-render-action.aspx. You can also check out the discussion on this other post here on SO: ASP.NET MVC Master Page Data