具有指定HTML ID的Html.ActionLink?

Pet*_*ter 37 css asp.net-mvc html-helper actionlink asp.net-mvc-2

我想用生成Html.ActionLink的HTML ID 生成,这样我就可以根据我的位置更改CSS.我有一MasterPage组链接,我想区分活动的"Tab"和Jquery更改活动的#id的css

现在我正在使用:

<%: Html.ActionLink("Some View", "Index", "controller")%>
Run Code Online (Sandbox Code Playgroud)

它产生:

<a href="/controller">Some View</a>
Run Code Online (Sandbox Code Playgroud)

我想生成:

<a id="something" href="/controller">Some View</a>
Run Code Online (Sandbox Code Playgroud)

那可能吗?我试过了:

<%: Html.ActionLink("Some View", "Index", "controller", new {id="blahbla")%>
Run Code Online (Sandbox Code Playgroud)

但这会产生:

<a href="/controller/Length?5">Some View</a>
Run Code Online (Sandbox Code Playgroud)

Kel*_*sey 52

你走在正确的轨道上.我不确定为什么它不适合你,因为你的代码有一个错误的错字} expected.您正在寻找以下内容:

 <%= Html.ActionLink("Test Link", "SomeAction", "SomeController",
         null, new {id = "someID" }) %> 
Run Code Online (Sandbox Code Playgroud)

哪个产生以下HTML:

<a href="/SomeController/SomeAction" id="someID">Test Link</a>
Run Code Online (Sandbox Code Playgroud)

编辑:我刚刚意识到问题是什么,因为我错误地阅读了你所尝试的内容.您正在使用错误的重载来传递idhtml元素.您可能将new { id="blah" }参数传递给routeValues参数,这将导致在构建路径链接时使用它,而不是htmlAttributes您想要的参数.

我认为你正在使用:

ActionLink(string linkText, string actionName, Object routeValues,
    Object htmlAttributes)
Run Code Online (Sandbox Code Playgroud)

当您需要使用的是以下重载时,就像我在上面的答案中所做的那样:

ActionLink(string linkText, string actionName, string controllerName,
    Object routeValues, Object htmlAttributes)
Run Code Online (Sandbox Code Playgroud)

这确保new { id="blah" }被传递到htmlAttributes参数中.


Pet*_*ter 6

试试这个:

<%: Html.ActionLink("Some View", "Index", "controller", null, new {id="something}")%>
Run Code Online (Sandbox Code Playgroud)