steavy
steavy

Reputation: 1576

using View with layout when both require specific Model

I`m writing an ASP.Net MVC application with Razor.

Assume that I have HomeController and some views for it.

 1. View1
 2. View2
 3. View3

All this views use common _MyLayout file, which should look like this:

When the links are clicked, the views are rendered by RenderBody() method. Each view is strongly typed: it requires its own Model.

Everything was fine untill I decided to add special Model to _MyLayout view.

But now I get error

The model item passed into the dictionary is of type 'TestUp.Models.UserModels.PendingTestsModel', but this dictionary requires a model item of type 'TestUp.Models.UserModels.UserNavigationModel'.

Here is controllers code

public ActionResult View1()
    {
        ModelForView1 model = new ModelForView1();
        return View(model);
    }
public ActionResult View2()
    {
        ModelForView2 model = new ModelForView2();
        return View(model);
    }
public ActionResult View3()
    {
        ModelForView3 model = new ModelForView3();
        return View(model);
    }

Shortly speaking if layout view doesn`t require model, specific method for View is invoked, model is created, passed to view and everything is ok. But now layout requires model as well so it crashes.

The question is: how do I elegantly resolve this problem?

Desired workflow is:

  1. View1 is requested
  2. Method in controller for this view is called, model instance created, passed to view
  3. Some method for layout is called, model for layout created, passed to layout.

Is it possible to make things work somehow like this?

Thanks.

Upvotes: 0

Views: 87

Answers (1)

Paul Fleming
Paul Fleming

Reputation: 24526

Create a base model type and have your specific view models extend it. This base model can have a property of type UserNavigationModel. The layout can accept the base model and use the new property as the model for the navigation menu.

public abstract class ModelBase
{
    public UserNavigationModel NavigationModel { get; set; }
}

public class ModelForView1 : ModelBase { ... }
public class ModelForView2 : ModelBase { ... }
public class ModelForView3 : ModelBase { ... }

View1:

@model ModelForView1

Layout:

@model ModelBase
@* use Model.NavigationModel for nav bar *@

Upvotes: 1

Related Questions