0

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?

amhed
  • 3,649
  • 2
  • 31
  • 56
Nithin Viswanathan
  • 3,245
  • 7
  • 39
  • 84

3 Answers3

2

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.

Community
  • 1
  • 1
Tim M.
  • 53,671
  • 14
  • 120
  • 163
0

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.

Jon Malcolm
  • 461
  • 3
  • 12
0

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.

Reza Abolfathi
  • 3,061
  • 2
  • 18
  • 14