2013-05-22 95 views
0

我在我的數據庫中有下表。MVC4 Url路由

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

我已經視圖模型&控制器創建並顯示該使用DBML。
http://example.com/Home/UserList
但是當我在細節上點擊鏈接,URL結構如下:
http://example.com/mymvc1/home/details/5

5是ID。

我並不想通過身份證,我想通過用戶名

ID應被自動轉換成用戶名。

我怎樣才能做到這一點?

回答

4

添加{username}路由,而不是ID有點像:

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

,然後在你的listning使用像

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

然後在你的控制器有:

public ActionResult View(string username) 

UPDATE :

請注意,如果用戶名是唯一的,以上只是一個好主意。否則,您可以將用戶名作爲可選參數,以便在網址中獲得該名稱。

像這樣:

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控制器