Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested ViewModels / Partial View problems in MVC

I have two views: a partial view, and a view that encapsulates the partial view using @Html.RenderPartial("_PartialView"). Each has its own ViewModel:

public class PartialViewModel 
{
    // properties, etc.
}

public class MainViewModel 
{
    public PartialViewModel p { get; set; }
    // properties, etc.
}

I'm getting dictionary errors when I load up the second view (the one that uses MainViewModel), because this view and the partial view it encapsulates are using two different ViewModels. I can't have them use the same ViewModel, because the partial view is rendered inside many other different views.

To be clear, both of these views contain forms, with the partial view representing all of the shared fields between forms. Given this, do I have any options, or am I simply attempting to do something that does not fit within the MVC design constraints?

like image 714
alex Avatar asked Nov 04 '14 17:11

alex


1 Answers

you are going to want to design this a little differently . The main view will have a Model - lets call it MainModel, and the partial View can have a Model - we'll call it PartialModel

public class PartialModel 
{
   /// props
}

public class MainViewModel 
{
    public PartialModel Partial { get; set; }
    // properties, etc.

    // per comments in other answer you may want something like this
    public MainViewModel()
    {
      Partial = new PartialModel();
    }
}

then your main View will have

@model MainViewModel

then in the middle of the main view you have something like

@{ Html.RenderPartial("myPartialView", Model.Partial); }

Notice the braces around Html.RenderPartial. They're needed because RenderPartial return is void.

When you render the partial view you can also pass in the Model to it, if it is designed properly then the model that the partial needs will already be accessable from the main view's model

like image 56
Scott Selby Avatar answered Sep 21 '22 13:09

Scott Selby