问题
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.
回答1:
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
回答2:
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.
来源:https://stackoverflow.com/questions/2593534/pass-data-to-master-page-with-asp-net-mvc