MVC4 URL路由

时间:2013-05-22 12:04:51

标签: asp.net-mvc

我的数据库中有以下表格。

Userid   username              usercity
1        amit                  mumbai
2        vishal                ahmedabad 
3        shekhar               indore
4        nitin                 bhopal
5        dhanraj               jaipur   

我已经创建了viewmodel&控制器并使用DBML显示它 http://example.com/Home/UserList
但是当我点击详情链接时,网址结构如下:
http://example.com/mymvc1/home/details/5

5是ID。

我不想传递ID,我想传递用户名

ID应自动转换为用户名。

我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:4)

{username}添加到路线而不是ID类似:

routes.MapRoute("ViewUser", "Somepath/View/{username}",
                    new { controller = "Users", action = "View" }
                );

然后在您的列表中使用

@Html.ActionLink("View User", "View", new { username = item.Username })

然后在你的控制器中有:

public ActionResult View(string username)

更新:

请注意,如果用户名是唯一的,则上述选项只是个好主意。否则,您可以将用户名作为可选参数,以便在URL中获取名称。

像这样:

routes.MapRoute("ViewUser", "Somepath/View/{userID}/{username}",
 new { controller = "Users", action = "View", username = UrlParameter.Optional },
 new { userID = @"\d+" } 
  );

然后是用户

@Html.ActionLink("View User", "View", new { userID = item.UserID, username = item.Username })

然后回到控制器中的int userID