Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.Net MVC: How to determine if you're currently on a specific view

Tags:

c#

asp.net-mvc

I need to determine if I'm on a particular view. My use case is that I'd like to decorate navigation elements with an "on" class for the current view. Is there a built in way of doing this?

like image 946
Jim Geurts Avatar asked Sep 02 '08 20:09

Jim Geurts


People also ask

How do you check if a view is partial or not?

Solution 1 There is no difference in the markup between a partial view and a view; the only difference is in how they are delivered to the browser. A partial view is sent via AJAX and must be consumed by JavaScript on the client side, while a View is a full postback. That's it.

How do I navigate to another view in MVC?

Call the appropriate /controller/action in your respective button click handlers. In your case for the register button handler direct it to /home/register. Have a view for your register functionality. In the register action of your home controller return the view you want to show.

Where will be the view for response is decided for a specific user request in MVC?

When ASP.NET MVC attempts to resolve a view template, it will first check within the \Views[Controller] specific directory, and if it can't find the view template there it will look within the \Views\Shared directory.

What does return View () in MVC do?

The default behavior of the View method ( return View(); ) is to return a view with the same name as the action method from which it's called. For example, the About ActionResult method name of the controller is used to search for a view file named About.


3 Answers

Here what i am using. I think this is actually generated by the MVC project template in VS:

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;
    }
like image 64
memical Avatar answered Oct 04 '22 02:10

memical


My current solution is with extension methods:

public static class UrlHelperExtensions
{
    /// <summary>
    /// Determines if the current view equals the specified action
    /// </summary>
    /// <typeparam name="TController">The type of the controller.</typeparam>
    /// <param name="helper">Url Helper</param>
    /// <param name="action">The action to check.</param>
    /// <returns>
    ///     <c>true</c> if the specified action is the current view; otherwise, <c>false</c>.
    /// </returns>
    public static bool IsAction<TController>(this UrlHelper helper, LambdaExpression action) where TController : Controller
    {
        MethodCallExpression call = action.Body as MethodCallExpression;
        if (call == null)
        {
            throw new ArgumentException("Expression must be a method call", "action");
        }

        return (call.Method.Name.Equals(helper.ViewContext.ViewName, StringComparison.OrdinalIgnoreCase) &&
                typeof(TController) == helper.ViewContext.Controller.GetType());
    }

    /// <summary>
    /// Determines if the current view equals the specified action
    /// </summary>
    /// <param name="helper">Url Helper</param>
    /// <param name="actionName">Name of the action.</param>
    /// <returns>
    ///     <c>true</c> if the specified action is the current view; otherwise, <c>false</c>.
    /// </returns>
    public static bool IsAction(this UrlHelper helper, string actionName)
    {
        if (String.IsNullOrEmpty(actionName))
        {
            throw new ArgumentException("Please specify the name of the action", "actionName");
        }
        string controllerName = helper.ViewContext.RouteData.GetRequiredString("controller");
        return IsAction(helper, actionName, controllerName);
    }

    /// <summary>
    /// Determines if the current view equals the specified action
    /// </summary>
    /// <param name="helper">Url Helper</param>
    /// <param name="actionName">Name of the action.</param>
    /// <param name="controllerName">Name of the controller.</param>
    /// <returns>
    ///     <c>true</c> if the specified action is the current view; otherwise, <c>false</c>.
    /// </returns>
    public static bool IsAction(this UrlHelper helper, string actionName, string controllerName)
    {
        if (String.IsNullOrEmpty(actionName))
        {
            throw new ArgumentException("Please specify the name of the action", "actionName");
        }
        if (String.IsNullOrEmpty(controllerName))
        {
            throw new ArgumentException("Please specify the name of the controller", "controllerName");
        }

        if (!controllerName.EndsWith("Controller", StringComparison.OrdinalIgnoreCase))
        {
            controllerName = controllerName + "Controller";
        }

        bool isOnView = helper.ViewContext.ViewName.SafeEquals(actionName, StringComparison.OrdinalIgnoreCase);
        return isOnView && helper.ViewContext.Controller.GetType().Name.Equals(controllerName, StringComparison.OrdinalIgnoreCase);
    }
}
like image 39
Jim Geurts Avatar answered Oct 04 '22 04:10

Jim Geurts


Here is something a little different, use a FilterAttribute:

    [NavigationLocationFilter("Products")]
    public ViewResult List()
    {
        return View();
    }

...

public class NavigationLocationFilterAttribute : ActionFilterAttribute
{
    public string CurrentLocation { get; set; }

    public NavigationLocationFilterAttribute(string currentLocation)
    {
        CurrentLocation = currentLocation;
    }

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var controller = (Controller)filterContext.Controller;
        controller.ViewData.Add("NavigationLocation", CurrentLocation);
    }
}

...

And in the view:

<%= ViewData["NavigationLocation"] %>
like image 21
Matt Hinze Avatar answered Oct 04 '22 03:10

Matt Hinze