ASP.NET路由传递字符串值

时间:2010-01-25 04:07:06

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

我正在尝试在基于ASP.NET MVC的网站上创建一个页面,其中一个页面允许通过用户名而不是ID进行选择。我原以为路线需要像:

routes.MapRoute(
  "CustomerView", "Customer/Details/{username}",
  new { username = "" }
);

routes.MapRoute(
  "Default", "{controller}/{action}/{id}",
  new { controller = "Home", action = "Index", id = "0" }
);

但每当我使用HTML.Actionlink时,我都会得到http://mysite.com/Customer/Details?username=valuehere。我认为通用路线如下:

routes.MapRoute(
  "CustomerView", "Customer/Details/{username}",
  new { controller="Customer", action = "Details", username = "" }
);

但我想如果它错误地应用哪一条路线会导致更多问题。

3 个答案:

答案 0 :(得分:2)

Customer控制器的Details方法是否具有“username”参数,而不是id参数?

如果参数不匹配,则将它们作为查询字符串变量附加。

答案 1 :(得分:1)

这有效:

routes.MapRoute(
  "CustomerView", "Customer/Details/{username}",
  new { controller="Customer", action = "Details", username = "" }
);

但在上面的问题中,我在第二个例子中犯的错误是我的意思:

routes.MapRoute(
  "CustomerView", "{controller}/{action}/{username}",
  new { controller="Customer", action = "Details", username = "" }
);

这只是意味着我必须为传递字符串值的每个实例专门声明一个路由。

答案 2 :(得分:1)

我不确定我完全理解这个问题......你说的是你想要的吗?

  1. 一个路由{controller}/{action}/{username},用于处理第3个令牌为字符串的URL,匹配字符串“username”参数的操作,以及

  2. 另一个路由{controller}/{action}/{id},它处理第3个令牌是整数的URL,匹配有整数“id”参数的动作?

  3. 如果有,请查看overload for MapRoute 4th argument specifying route constraints。它应该让你做这样的事情:

    routes.MapRoute(
        "CustomerView", "{controller}/{action}/{username}",
        new { controller="Customer", action = "Details", username = "" }
        new { username = @"[^0-9]+" }
    );
    

    此(未经测试的)约束应使{username}路由匹配第3个令牌包含至少一个非数字字符的任何内容。

    当然,如果用户名完全由数字组成是合法的,那么这可能不适合您。在这种情况下,您可能需要为接受用户名而不是ID的每个操作创建专用路由。