0

I have a page with following on top:

@model AppMainModel
@{
    ViewData["Title"] = "Home Page";
}

I would like to use AppMainModel and its properties in its master/layout page. Strongly typed if possible (e.g. avoid ViewData and the like).

Is this possible?

AngryHacker
  • 59,598
  • 102
  • 325
  • 594
  • I assume you mean the layout page? Just add `@model AppMainModel` to it as well but it's unclear why you would want to tie a layout page to a model –  Nov 13 '15 at 22:07
  • @StephenMuecke Yes, the layout page. The bootstrap nav bar is in the layout page and i need it to be data driven. That is the reason. – AngryHacker Nov 13 '15 at 22:09
  • 1
    The problem is that your layout can now only be used by a view that has `@model AppMainModel`. I suspect what you really want is to use `@Html.Action()` to call a method that returns a partial view of the nav bar –  Nov 13 '15 at 22:12
  • I think this is the same question: [How to pass viewmodel to a layout/master page?](https://stackoverflow.com/questions/12946130/how-to-pass-viewmodel-to-a-layout-master-page) – Tim Abell Jul 02 '20 at 11:21

3 Answers3

0

The ViewModel data is available to the layout page. You can consider having a page viewmodel class with the common data if you want it to be strongly typed in the layout page. If not, simply pass in the common thing using the dynamic nature of ViewData. You might even apply a global filter to set up the common data if it seems appropriate. Solution From here

You may also try this solution: http://forums.asp.net/t/1799746.aspx?How+to+pass+a+value+to+the+LoginDisplay+from+HomeController+that+will+display+on+all+pages

0

You can set the @model on the layout page as well:

@model AppMainModel

<html>
<head>
   <title>@Model.Title</title>
</head>
...
</html>

However, you must make sure everytime you use this layout you pass a model that inherits from AppMainModel.

Max Toro
  • 28,282
  • 11
  • 76
  • 114
0

To avoid being non-strongly typed on the _Layout page, i suggest you to take a look at the following great @jgauffin blog post about Getting information into the Layout without using ViewBag.

Using a LayoutViewModel in summary:

  • Create a viewmodel with all the types/fields you need on your _Layout page
  • Wrap handling of this LayoutViewModel into a BaseController class (that your other controllers inherit from) overriding its OnResultExecuting() method
  • Create a Viewbase layout class that will inherit WebViewPage, and register it in web.config to use your Viewbase layout model as pageBaseType

An example: I use this approach to pass meta field values to my _Layout page.

kayess
  • 3,384
  • 9
  • 28
  • 45
  • That link is now dead, page is archived here https://web.archive.org/web/20160116114307/http://blog.gauffin.org/2011/09/12/getting-information-into-the-layout-without-using-viewbag/ – Stephen Angell Oct 14 '22 at 13:33