2010-12-05 47 views
53

我在下面的剃鬚刀頁面上有鏈接。Razor actionlink autogenerating?length = 7 in URL?

@Html.ActionLink("Create New Profile", "Create", "Profile", new { @class="toplink" }) 

我看到的是低於

<a href="/admin/profile/create?length=7" class="toplink">Create New Profile</a> 

當我點擊鏈接頁面查看源代碼。網址如下所示。

http://localhost:54876/admin/profile/create?length=7 

我不想要?長度= 7。爲什麼這是自動生成的。

+0

它必須與您的路線有關。默認情況下,`ActionLink`應該生成`/ Profile/Create`的href。其中`Profile`是控制器參數,`Create`是動作方法參數。 `/ admin`被放入href的事實突出了這個問題。你能展示你的路線嗎? – RPM1984 2010-12-05 07:43:23

回答

85

ActionLink覆蓋您正在使用匹配(string linkText, string actionName, Object routeValues, Object htmlAttributes)重寫。所以你的「Profile」值被傳遞給routeValues參數。此函數相對於此參數的行爲是將所有公共屬性添加到它並將其添加到用於生成鏈接的路由值列表中。由於一個String只有一個公共屬性(Length),所以最終的結果是「length = 7」。

要使用正確的過載是(string linkText, string actionName, string controllerName, Object routeValues, Object htmlAttributes),你叫它魔神這樣:

@Html.ActionLink("Create New Profile", "Create", "Profile", new {}, new { @class="toplink"}) 
7

我不知道這個確切原因,但將其更改爲:

@Html.ActionLink("Create New Profile", "Create", "Profile", new {}, new { @class="toplink" }) 

我不知道是哪個超載MVC是撿你離開時關閉的最後一個參數(htmlattributes是增加了一個),但這將解決它。其中一天,我會調查並弄清楚究竟發生了什麼。

+0

這種爲我工作,但我仍然結束了一個流氓鏈接...我有`〜/帳戶/管理/用戶= ortund`,而我需要的是'〜/帳戶/管理/ ortund` – Ortund 2014-09-11 12:46:13

+0

你可以只需使用null即可。至少這是我總是使用的。 – 2015-08-04 17:35:41

0

另外一點需要注意的,因爲你所定義的控制器在@ActionLink,你可能不需要做,例如,您的「創建新配置文件」@ActionLink表示的視圖可能是「/admin/profile/index.cshtml」,這是一個列出現有配置文件的視圖,在這種情況下,您不需要在作爲@ActionLink@ActionLink已經相對於ProfileController,所以您的@ActionLink可能是

@Html.ActionLink("Create New Profile", "Create", null, new { @class="toplink" }) 

我用null而不是new{}作爲標記的答案,我認爲這是比較合適的我自己。 ActionLink重載並不是最直接的事情。