ASP.NET MVC路由中未传递的参数值

时间:2011-01-25 16:18:58

标签: asp.net-mvc parameters asp.net-mvc-routing

我正在学习如何在ASP.NET MVC中创建自定义路由并且遇到了障碍。在我的Global.asax.cs文件中,我添加了以下内容:

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.MapRoute(
        "Default", // Route name
        "{controller}/{action}/{id}", // URL with parameters
        new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
    );

    // My Custom Route.
    routes.MapRoute(
        "User_Filter",
        "home/filter/{name}",
        new { controller = "Home", action = "Filter", name = String.Empty }
    );
}

我的想法是能够导航到http://localhost:123/home/filter/mynameparam。这是我的控制器:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    public ActionResult Filter(string name)
    {
        return this.Content(String.Format("You found me {0}", name));
    }
}

当我导航到http://localhost:123/home/filter/mynameparam调用控制器方法Filter时,参数name始终为null

有人可以指出我构建自定义路线的正确方法,以便将网址中的名称部分传递给name的{​​{1}}参数。

2 个答案:

答案 0 :(得分:7)

Default路线应该是最后一条路线。 试试这种方式:

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    // My Custom Route.
    routes.MapRoute(
        "User_Filter",
        "home/filter/{name}",
        new { controller = "Home", action = "Filter", name = String.Empty }
    );

    routes.MapRoute(
        "Default", // Route name
        "{controller}/{action}/{id}", // URL with parameters
        new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
    );
}

答案 1 :(得分:1)

我相信你的路线需要反过来?

路由按顺序处理,因此如果第一个(默认的,OOTB)路由与URL匹配,那就是将要使用的路由。