How to pass the model from the razor page to its master/layout page?

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-12 02:23:28

问题


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 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.



来源:https://stackoverflow.com/questions/33702441/how-to-pass-the-model-from-the-razor-page-to-its-master-layout-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!