Tutorial :Change menus depending on controller in ASP.NET MVC



Question:

In a master-page, how can I know, which controller I am currently using? Is there some kind of context-object, that can give me that sort of information?

Standard menu

<ul>  <li>Fire</li>  <li>Ice</li>  <li>Water</li>  </ul>  

Menu if I am in the water-controller

<ul>  <li>Fire</li>  <li>Ice</li>  <li class="selected">Water</li>  </ul>  

If I have a menu in my Site.master, where each menu-item refers to a different controller, how can I highlight each menu-item depending on, which controller I am currently in?

I know I can get the url from request.Servervariables and then work some string-magic, but there must be a better way - some kind of context-object?


Solution:1

Here are two helper methods I use for checking if its the current controller or even current action. The you can use the helpers to determine whether to add class="selected" or not.

public static bool IsCurrentController(this HtmlHelper helper,                                          string controllerName)  {      string currentControllerName = (string)helper.ViewContext.RouteData.                                     Values["controller"];        if (currentControllerName.Equals(controllerName,          StringComparison.CurrentCultureIgnoreCase))      {         return true;      }        return false;  }    public static bool IsCurrentAction(this HtmlHelper helper, string actionName,                                      string controllerName)  {      string currentControllerName = (string)helper.ViewContext.RouteData                                     .Values["controller"];      string currentActionName = (string)helper.ViewContext.RouteData                                 .Values["action"];        if (currentControllerName.Equals(controllerName,          StringComparison.CurrentCultureIgnoreCase) &&           currentActionName.Equals(actionName,                                    StringComparison.CurrentCultureIgnoreCase))      {          return true;      }        return false;  }  


Solution:2

The ViewContext property of the ViewMasterPage contains the Controller and RouteData for the request. You could look at the type name of the controller or the controller key in the route data to find out which controller was invoked.


Solution:3

You can do a

ViewContext.Controller.GetType().Name

That should do it.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »