I have a menu and I used a cookie in order to set the menu as selected by refreshing. The menu is common to all classes, so I put it in the _layout.cshtml, but the same time I want a controller for this layout because there some function to set the menu as highlight. Can I create a controller for this?
3 Answers
Yes, you can call @Html.Action
or @Hmtl.RenderAction
to invoke a controller from the view. But this borders on mixing of concerns, as now your view is actively calling your controller.
The better approach is often to pass the appropriate data to the view as part of your view model.
But the same time I want a controller for this layout because there some function to set the menu as highlight.
If you are doing something basic like highlighting the current page, there may be a simpler solution. You could put the current page ID into the ViewBag
and retrieve that value in your main _Layout file and use it to select the appropriate item.
-
here we don't use viewbag. – Nithin Viswanathan Apr 05 '13 at 09:49
-
Okay, then one of the other options I provided should work. I don't use ViewBag often, but it's good for small pieces of data like this. – Tim M. Apr 05 '13 at 09:50
-
What I need is I set the cookie, I have to set it as selected but when I put this url in to new tab it takes the old cookie. – Nithin Viswanathan Apr 05 '13 at 09:52
-
Then perhaps go with the `RenderAction` approach that uses a controller to render the view, and have whatever cookie-related logic you need in there. – Tim M. Apr 05 '13 at 09:57
-
Is there any other article for referring?I am new in mvc – Nithin Viswanathan Apr 05 '13 at 10:00
-
The article that @JonMalcolm linked is pretty good: http://haacked.com/archive/2009/11/17/aspnetmvc2-render-action.aspx – Tim M. Apr 05 '13 at 10:01
-
ok.thanx..I will give you take your answer after getting the answer – Nithin Viswanathan Apr 05 '13 at 10:03
Partial actions may be what you looking for here - this article may be some help. It relates to MVC2 but the principles remain the same.

- 461
- 3
- 12
create an action for menu, and put menu ui in the view, and then call Html.Action("menu action name","controllern name") on layout page.

- 3,061
- 2
- 18
- 14