Pass data to Master Page with ASP.NET MVC

2019-08-29 03:02发布

I have a hybrid ASP.NET WebForms/MVC project. In my Master Page, I have a "menu" User Control and a "footer" User Control. Anyways. I need to pass some data (2 strings) to my "menu" User Control on my Master Page (to select the current tab in my menu navigation, etc.) My views are strongly-typed to my data model. How can I push data from my controller to my menu or at least allow my master page to access some data pre-defined in my controller?

Note: I understand this violates pure ASP.NET MVC, but like I said, it is a hybrid project. The main purpose of my introduction to ASP.NET MVC into my project was to have more control over my UI for certain situations only.

2条回答
手持菜刀,她持情操
2楼-- · 2019-08-29 03:35

You can use ViewData to share data between the Controller and View that is not in the model. In the Controller, do something like ViewData["menu"] = myMenu; and then in the View do <%= ViewData["menu"] %>. You can pass objects but you need to cast the ViewData[key] back to the object type in the View.

Another way to do this is to put your menus and other non-Model related data needs into a separate controller. Then you can use RenderAction to call the action in your navigation controller that generates the menu. Hack has a blog post on RenderAction that explains this in more detail.

I lean towards using ViewData for temporary values from the controller like select lists and a RenderAction for unrelated things such as the main site navigation.

查看更多
我只想做你的唯一
3楼-- · 2019-08-29 03:45

Put your strings into the ViewData collection,

ViewData["MenuString1"] = "My First String";
ViewData["MenuString2"] = "My Second String";

and retrieve them in the Master Page like this:

myMenu.Property1 = ViewData["MenuString1"].ToString();
myMenu.Property2 = ViewData["MenuString2"].ToString();

http://nerddinnerbook.s3.amazonaws.com/Part6.htm

查看更多
登录 后发表回答