简体   繁体   中英

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?

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

You can do this, but in your controller you're going to need to declare a new MainViewModel and assign to its PartialViewModel a new PartialViewModel.

Ex:

public class Controller {
    public ActionResult Index(){
        var mainViewModel = new MainViewModel { PartialViewModel = new PartialViewModel() };
        return View(mainViewModel);
    }
}

Now, I would delegate the creation of these models to a factory, but that's more advanced and not necessary until you get into refactoring.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM