route net mvc httpget examples attribute asp c# asp.net-mvc routing

c# - httpget - Asp.Net MVC: ¿Cómo obtengo la url virtual para el controlador/vista actual?



route controller mvc 5 (5)

¿Es posible obtener la ruta / URL virtual asociada con una acción de controlador o en una vista? Vi que la Vista previa 4 agregó el complemento LinkBuilder.BuildUrlFromExpression, pero no es muy útil si desea usarlo en el maestro, ya que el tipo de controlador puede ser diferente. Cualquier pensamiento es apreciado


Puede usar <% = Url.Action (action, controller, values)%> para construir la URL desde dentro de la página maestra.

¿Estás haciendo esto para resaltar una pestaña para la página actual o algo así?

De ser así, puede usar ViewContext desde la vista y obtener los valores que necesita.


Escribí una clase de ayuda 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.


Puede obtener esos datos de ViewContext.RouteData. A continuación hay algunos ejemplos de cómo acceder (y usar) esa información:

/// Estos se agregan a mi viewmappage, viewpage y viewusercontrol clases base:

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


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 %>


Esto funcionó para mí:

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

Devuelve la Url actual como tal; /Home/About

Tal vez hay una forma más simple de devolver la cadena de ruta real?