2011-09-01 176 views
0

我(拼命地)試圖從我的一個控制器創建鏈接。HtmlHelper.GenerateRouteLink沒有給出預期的結果

它應該看起來像這樣:
http://localhost:50074/User/Profile?UserId=17&key=agasgqwefq323432r13dfd

相關的(儘管可能是錯誤的)路線:

routes.MapRoute(
      "UsersRoute", // Route name 
      "{controller}/{action}/{userId}/{key}", 
      new { controller = "User", action = "Profile",userId=UrlParameter.Optional,key=UrlParameter.Optional }); 

和鏈接代碼:

HtmlHelper.GenerateRouteLink(requestContext, RouteTable.Routes, "MyLinkText", "UsersRoute", new RouteValueDictionary(new { userId = userId, key = HashPassword(password) }), null);   

(其中我送請求上下文:HttpContext.Request.RequestContext

目前這給了我:

<a href="http://Account/Register/29/E96303852080B94DC230611A3F4806" target="_blank">MyLinkText</a> 

任何(來自我稱之爲GenerateRouteLink是帳戶/註冊,和我不知道如何創建一個正確的,如果真正需要的情況下)幫助將不勝感激。

回答

2

在你的路由定義的URL會的形式爲:

{controller}/{action}/{userId}/{key} 

,所以我不看你怎麼可能指望形式的URL({controller}/{action})當您指定useridkey令牌:

/User/Profile?UserId=17&key=agasgqwefq323432r13dfd 

爲什麼不簡單地只保留默認的url定義?

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

然後,你可以通過簡單地獲得所需形式的URL:

@Html.ActionLink(
    "MyLinkText", 
    "Profile", 
    "User", 
    new { userId = userId, key = HashPassword(password) }, 
    null 
) 
+0

感謝您選擇的答案,但生成的鏈接是一樣的.. –

+0

我知道該怎麼做,從一個視圖,問題是我不能這樣做從CS ..(即控制器) –

+1

@Oren A,在控制器中,您可以使用'Url.Action'方法。 –