问题
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?
回答1:
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
回答2:
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
.
回答3:
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 inweb.config
to use your Viewbase layout model aspageBaseType
An example: I use this approach to pass meta field values to my _Layout page.
来源:https://stackoverflow.com/questions/33702441/how-to-pass-the-model-from-the-razor-page-to-its-master-layout-page