t_plusplus
t_plusplus

Reputation: 4209

Partial Views with view models different to the main view

My home-screen has a view model of DashboardViewModel. It has PartialViews with their own ViewModels such as CustomerSearchViewModel and SelectProductViewModel.

All three ViewModels are separate.

When I run the application I get this error:

The model item passed into the dictionary is of type 'Invoice.Web.ViewModels.DashboardViewModel', but this dictionary requires a model item of type 'Invoice.Web.ViewModels.SearchCustomerWindowVM'.

I wonder what should I do to resolve this issue.

As planned, the Home screen will eventually integrate a lot of PartialViews with their own view models. Do I declare the Partial-view-models inside the DashboardViewModel? or do I simply have a single big DashboardViewModel for all partialViews to come?

Upvotes: 0

Views: 539

Answers (2)

Brandon O'Dell
Brandon O'Dell

Reputation: 1171

Another option is to use Html.Action() or Html.RenderAction(). This allows you to call a completely separate controller from your parent view, and return a completely different, non associated model. Here is a pretty good explanation on both rendering Partial Views and Actions. http://www.midnight-coding.com/2013/01/partial-vs-action-vs-renderpartial-vs-renderaction.html

Upvotes: 1

Shyju
Shyju

Reputation: 218732

You can have your partial view viewmodels as properties of your main viewmodel and call Html.Partial and pass these properties.

public class DashBoardVM
{
  public string Name { set;get;}
  public CustomerSearchVM CustomerSearch { set; get;}

  public DashBoardVM()
  {
    CustomerSearch =new CustomerSerachVM();
  }
}

In your dashboard view,

@model DashBoardVM
<h2>@Model.Name</h2>
@Html.Partial("CustomerSearch",Model.CustomerSearch)

Assuming CustomerSearch partial view is strongly typed o CustomerSearchVM class.

Upvotes: 2

Related Questions