Problems with nested ViewModels / Partial View in MVC

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

public class PartialViewModel 
{
    // properties, etc.
}

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

I get dictionary errors when loading the second view (the one that uses the MainViewModel) because this view and the partial view that it encapsulates use two different ViewModels. I cannot get them to use the same ViewModel because a partial view is displayed in many other different views.

To be clear, both of these views contain forms , and a partial view represents all the common fields between the forms. Given this, do I have any options or am I just trying to do something that does not comply with the limitations of MVC design?

+4
source share
2 answers

you will want to design this a little differently. The main view will have a model - allows you to call it MainModel, and a partial view can have a model - we will call itPartialModel

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 be

@model MainViewModel

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

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

Note the braces around the Html.RenderPartial. They are necessary because the RenderPartial return is invalid.

, , ,

+3

, MainViewModel PartialViewModel PartialViewModel.

:

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

factory, , .

+2

All Articles