简体   繁体   English

Asp.Net MVC:如何获取当前控制器/视图的虚拟URL?

[英]Asp.Net MVC: How do I get virtual url for the current controller/view?

Is it possible to get the route/virtual url associated with a controller action or on a view? 是否可以获取与控制器操作或视图关联的路由/虚拟URL? I saw that Preview 4 added LinkBuilder.BuildUrlFromExpression helper, but it's not very useful if you want to use it on the master, since the controller type can be different. 我看到Preview 4添加了LinkBuilder.BuildUrlFromExpression助手,但如果你想在master上使用它,它不是很有用,因为控制器类型可能不同。 Any thoughts are appreciated. 任何想法都表示赞赏。

I always try to implement the simplest solution that meets the project requirements. 我总是尝试实施满足项目要求的最简单的解决方案。 As Enstein said, "Make things as simple as possible, but not simpler." 正如恩斯坦所说,“让事情变得尽可能简单,但并不简单。” Try this. 尝试这个。

<%: Request.Path %>

This worked for me: 这对我有用:

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

It returns the current Url as such; 它会返回当前的Url; /Home/About

Maybe there is a simpler way to return the actual route string? 也许有一种更简单的方法来返回实际的路由字符串?

You can get that data from ViewContext.RouteData. 您可以从ViewContext.RouteData获取该数据。 Below are some examples for how to access (and use) that information: 以下是如何访问(和使用)该信息的一些示例:

/// These are added to my viewmasterpage, viewpage, and viewusercontrol base classes: ///这些被添加到我的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);
}

/// Some extension methods that I added to the UrlHelper class. ///我添加到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());
    }
}

You can use <%= Url.Action(action, controller, values) %> to build the URL from within the master page. 您可以使用<%= Url.Action(action,controller,values)%>从母版页中构建URL。

Are you doing this to maybe highlight a tab for the current page or something? 你这样做是为了突出当前页面的标签或什么?

If so you can use ViewContext from the view and get the values you need. 如果是这样,您可以从视图中使用ViewContext并获取所需的值。

I wrote a helper class that allows me to access the route parameters. 我写了一个帮助类 ,允许我访问路由参数。 With this helper, you can get the controller, action, and all parameters passed to the action. 使用此帮助程序,您可以获取控制器,操作以及传递给操作的所有参数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在ASP.NET MVC 5项目中获得“添加控制器”和“添加视图”菜单选项? - How do I get the “Add Controller” and “Add View” menu options in my ASP.NET MVC 5 project? 如何将带有自己的控制器的局部视图添加到 asp.net mvc 4 中的另一个视图 - How do I add a partial view with its own controller to another view in asp.net mvc 4 如何在 ASP.NET MVC controller 中获取 url - How to get url in ASP.NET MVC controller 如何在 ASP.NET MVC 中的控制器外部生成 URL? - How do I generate a URL outside of a controller in ASP.NET MVC? 如何在 ASP.NET Core MVC“待办事项”应用程序中提取 URL 的文件名并在视图中显示给用户? - How do I extract the filename of a URL in a ASP.NET Core MVC "To Do" app and show it to the user in the View? 如何将DateTime参数从View传递到ASP.net MVC5中的Controller? - How do I pass DateTime parameters from View to Controller in ASP.net MVC5? ASP.NET MVC如何将控制器操作指向其他视图? - ASP.NET MVC How do I point a controller action to a different view? 在ASP.NET MVC控制器中,如何获取Redirect(string URL)方法不附加“#”? - In an ASP.NET MVC Controller, how can I get the Redirect(string URL) method to not append a '#'? 如何在ASP.NET MVC中允许/ Controller / Id? - How do I allow /Controller/Id in ASP.NET MVC? 如何将 ID 传递给 ASP.NET MVC 中的控制器? - How do I pass an ID to the controller in ASP.NET MVC?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM