Asp.Net MVC: Как мне получить виртуальный URL для текущего контроллера / представления? - PullRequest
20 голосов
/ 30 сентября 2008

Можно ли получить маршрут / виртуальный URL, связанный с действием контроллера или в представлении? Я видел, что в Preview 4 добавлен помощник LinkBuilder.BuildUrlFromExpression, но он не очень полезен, если вы хотите использовать его на ведущем устройстве, поскольку тип контроллера может отличаться. Любые мысли приветствуются.

Ответы [ 5 ]

23 голосов
/ 25 января 2011

Я всегда стараюсь реализовать самое простое решение, которое соответствует требованиям проекта. Как сказал Энштейн: «Сделай все как можно проще, но не проще». Попробуй это.

<%: Request.Path %>
19 голосов
/ 28 марта 2009

Это сработало для меня:

<%= this.Url.RouteUrl(this.ViewContext.RouteData.Values) %>

Возвращает текущий URL как таковой; /Home/About

Может быть, есть более простой способ вернуть фактическую строку маршрута?

14 голосов
/ 12 августа 2009

Вы можете получить эти данные из ViewContext.RouteData. Ниже приведены некоторые примеры того, как получить доступ (и использовать) эту информацию:

/// Они добавлены в мои базовые классы viewmasterpage, viewpage и viewusercontrol:

public bool IsController(string controller)
{
    if (ViewContext.RouteData.Values["controller"] != null)
    {
        return ViewContext.RouteData.Values["controller"].ToString().Equals(controller, StringComparison.OrdinalIgnoreCase);
    }
    return false;
}
public bool IsAction(string action)
{
    if (ViewContext.RouteData.Values["action"] != null)
    {
        return ViewContext.RouteData.Values["action"].ToString().Equals(action, StringComparison.OrdinalIgnoreCase);
    }
    return false;
}
public bool IsAction(string action, string controller)
{
    return IsController(controller) && IsAction(action);
}

/// Некоторые методы расширения, которые я добавил в класс UrlHelper.

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);
    }

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

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

        return helper.ViewContext.Controller.GetType().Name.Equals(controllerName, StringComparison.OrdinalIgnoreCase);
    }

    /// <summary>
    /// Determines if the current request is on the specified controller
    /// </summary>
    /// <typeparam name="TController">The type of the controller.</typeparam>
    /// <param name="helper">The helper.</param>
    /// <returns>
    ///     <c>true</c> if the current view is on the specified controller; otherwise, <c>false</c>.
    /// </returns>
    public static bool IsController<TController>(this UrlHelper helper) where TController : Controller
    {
        return (typeof(TController) == helper.ViewContext.Controller.GetType());
    }
}
3 голосов
/ 30 сентября 2008

Вы можете использовать <% = Url.Action (действие, контроллер, значения)%> для создания URL-адреса из главной страницы.

Вы делаете это, чтобы выделить вкладку для текущей страницы или что-то в этом роде?

Если это так, вы можете использовать ViewContext из представления и получить нужные значения.

1 голос
/ 01 марта 2009

Я написал вспомогательный класс , который позволяет мне получить доступ к параметрам маршрута. С помощью этого помощника вы можете получить контроллер, действие и все параметры, переданные действию.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...