如何在htmlhelper中获取路由名称?

时间:2015-09-01 16:20:37

标签: c# asp.net-mvc razor routes

我想在我的html助手中获取当前路由名称,但我不知道如何制作它。

我认为解决方案是在post这篇文章中,但我不知道如何创建RouteCollectionExtions。

目前我的代码是:

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

public static class RouteCollectionExtensions
    {
        public static Route MapRouteWithName(this RouteCollection routes, string name, string url, object defaults, object constraints)
        {
            Route route = routes.MapRoute(name, url, defaults, constraints);
            route.DataTokens = new RouteValueDictionary();
            route.DataTokens.Add("RouteName", name);

            return route;
        }
    }

    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollectionExtensions routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.IgnoreRoute("favicon.ico");

            // Default
            routes.MapRoute ("Default", "", new { controller = "Home", action = "Index", id = UrlParameter.Optional });
            outes.MapRouteWithName("HomeFr", "fr", new { controller = "Home", action = "Index" });
        }
    }

你知道为什么编译器说:

  

'MyNamespace.RouteCollectionExtensions'不包含'MapRoute'的定义和最佳扩展方法重载'System.Web.Mvc.RouteCollection.Extensions.MapRoute(System.web.Routing.RouteCollection,string,string,string [ ])'有一些无效的论点。

感谢您的帮助。 的问候,

1 个答案:

答案 0 :(得分:2)

为了使用您建议的链接,这就是您的RouteConfig的样子:

(我放弃了约束,因为我没有看到他在示例中使用它)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace MvcApplication1
{
    public static class RouteCollectionExtensions
    {
        public static Route MapRouteWithName(this RouteCollection routes, string name, string url, object defaults)
        {
            Route route = routes.MapRoute(name, url, defaults);
            route.DataTokens = new RouteValueDictionary();
            route.DataTokens.Add("RouteName", name);

            return route;
        }
    }


    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.MapRouteWithName(
                "myRouteName",
                "{controller}/{action}/{username}",
                new { controller = "Home", action = "List" }

                );
        }
    }
}