2008-09-30 16 views

Respuesta

14

usted puede conseguir que los datos de ViewContext.RouteData. A continuación se presentan algunos ejemplos de cómo acceder (y usar) que la información:

/// Estos se añaden a mis viewmasterpage, clases ViewPage, y base 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); 
} 

/// algunos métodos de extensión que Agregué a la clase 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()); 
    } 
} 
+0

Advertencia: Este código ya no funciona en ASP.NET MVC 5. – qJake

+0

@qJake Entonces cómo compartir datos entre controladores en MVC5? – Mrunal

+0

@Mrunal Esta pregunta no se trata de compartir datos entre los controladores, sino más bien de cómo ver las rutas asociadas con un controlador. Sé que es posible con ASP.NET MVC 5 (ahora ASP.NET Core), pero no conozco la sintaxis de forma directa. – qJake

3

Puede utilizar <% = Url.Action (acción, controlador, valores)%> para construir la URL desde la página principal.

haces esto a tal resaltar una pestaña de la página actual o algo?

Si esta manera puede utilizar ViewContext de la vista y obtener los valores que necesita.

1

escribí a helper class que me permite acceder a los parámetros de la ruta. Con esta ayuda, puede obtener el controlador, la acción y todos los parámetros pasados ​​a la acción.

18

Esto funcionó para mí:

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

Devuelve la URL actual como tal; /Home/About

Tal vez hay una manera más sencilla de devolver la cadena de ruta real?

22

Siempre trato de implementar la solución más simple que cumpla con los requisitos del proyecto. Como dijo Enstein, "haz las cosas lo más simples posible, pero no más simples". Prueba esto.

<%: Request.Path %> 
+0

Gracias, fácil y simple +1 – Deano

Cuestiones relacionadas