1

I need to send 2 different Models, one to Index view and another one to _Layout.cshtml, how I can do it?

My HomeController:

[Route("")]
public ActionResult Index()
{
    HomeViewModel model = new HomeViewModel();
    model.A = _repoA.GetLatest(4);
    model.B = _repoB.GetLatest(4);
    model.C = _repoC.GetLatest(4);
    return View(model);
}

I don't like using ViewBag, ViewData & ..., I'm looking for passing the model in same way as we passing model to Views.

Mehdi Dehghani
  • 10,970
  • 6
  • 59
  • 64
  • possible duplicate of [ASP.NET MVC Razor pass model to layout](http://stackoverflow.com/questions/4154407/asp-net-mvc-razor-pass-model-to-layout) – Lordbalmon Aug 08 '15 at 19:52
  • 1
    Why not create a partial view with the model and render it in the layout. – pool pro Aug 08 '15 at 20:59
  • That's sounds great, but I prefer do it without this solution, is there any way to sending model direct to _layout? – Mehdi Dehghani Aug 08 '15 at 21:15
  • 1
    Use a partial view or child action. Many examples -- See [here](http://stackoverflow.com/questions/11459390/asp-net-mvc-3-partial-view-in-layout-page), [here](http://stackoverflow.com/questions/10552502/passing-data-to-a-layout-page), [here](http://stackoverflow.com/questions/5938837/asp-net-mvc-how-to-have-a-controller-in-shared-view)... – Jasen Aug 08 '15 at 21:25
  • Please read the question again, I wanna send to both of `index view` & `partial view` !!! – Mehdi Dehghani Aug 09 '15 at 04:30

2 Answers2

3

You can place this in your Layout to load a partial each time... Pretty useful for loading in a piece of a dynamic menu or a widget on each page.

Along with this line in your layout you can just do your Index page as you normally would.

@{ Html.RenderAction("_widget", "Home"); }
Mike Wallace
  • 543
  • 4
  • 15
1

You'll need to send it along in the ViewBag. I found the best bet was to make an abstract controller:

public abstract class ApplicationController : Controller
{
    protected ApplicationController()
    {
         UserStateViewModel = new UserStateViewModel();
         //Modify the UserStateViewModel here.
         ViewBag["UserStateViewModel"] = UserStateViewModel;
    }

    public UserStateViewModel UserStateViewModel { get; set; }
}

Then, have all of your controllers inherit from this abstract controller.

In your _Layout.cshtml (or whatever you called it), you'll need to include the following at the top:

@{
     var userState = (UserStateViewModel)ViewBag.UserStateViewModel;
}

Duplicate but refined from the 2nd answer to ASP.NET MVC Razor pass model to layout.

Community
  • 1
  • 1
  • Is there a better way to do this? it seems that it couples your controller to the View. The whole point of the MVC pattern is to be able to decouple. – leat Feb 21 '23 at 07:27