Asp.Net MVC: Wie kann ich virtuelle URL für die aktuelle Controller / Ansicht zu erhalten?

StackOverflow https://stackoverflow.com/questions/151963

  •  02-07-2019
  •  | 
  •  

Frage

Ist es möglich, die Strecke / virtuelle URL zu bekommen mit einer Controller-Aktion zugeordnet oder auf einen Blick? Ich sah, dass Preview 4 hinzugefügt LinkBuilder.BuildUrlFromExpression Helfer, aber es ist nicht sehr nützlich, wenn Sie es auf dem Master verwenden möchten, da die Controller-Typ unterschiedlich sein kann. Alle Gedanken sind willkommen.

War es hilfreich?

Lösung 3

Sie können diese Daten von ViewContext.RouteData erhalten. Im Folgenden sind einige Beispiele dafür, wie diese Informationen zugreifen (und benutzen):

/// Diese werden zu meinem Viewmaster, viewpage und Viewusercontrol Basisklassen:

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

/// Einige Erweiterungsmethoden, die ich die UrlHelper Klasse hinzugefügt.

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

Andere Tipps

Ich versuche immer die einfachste Lösung zu implementieren, die die Projektanforderungen erfüllen. Wie Enstein sagte: „Mache die Dinge so einfach wie möglich, aber nicht einfacher.“ Versuche dies.

<%: Request.Path %>

Das funktioniert für mich:

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

Es gibt die aktuelle URL als solche; /Home/About

Vielleicht gibt es einen einfacheren Weg, um das tatsächliche Route-String zurück?

Sie können mit <% = Url.Action (Aktion, Controller, Wert)%> die URL innerhalb der Master-Seite bauen.

Sie dies tun, um vielleicht eine Registerkarte für die aktuelle Seite oder etwas hervorheben?

Wenn ja Sie Viewcontext aus der Sicht verwenden können und die Werte, die Sie brauchen.

Ich schrieb eine Hilfsklasse , die mir erlaubt, die Routenparameter zugreifen. Mit diesen Helfern, können Sie den Controller, Aktion erhalten, und alle Parameter an die Aktion übergeben.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top