2010-12-05 49 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重载并不是最直接的事情。