Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
253 views
in Technique[技术] by (71.8m points)

css - Html.ActionLink with a specified HTML id?

I'd like to give the like generated with an Html.ActionLink an HTML id so I can change the CSS depending on where I am. I have a MasterPage with a set of links and I'd like to distinguish the active "Tab" with Jquery changing the css of that active #id

Right now I'm using:

<%: Html.ActionLink("Some View", "Index", "controller")%>

It generates:

<a href="/controller">Some View</a>

I'd like to generate:

<a id="something" href="/controller">Some View</a>

Is that possible? I've tried:

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

But that generates:

<a href="/controller/Length?5">Some View</a>
question from:https://stackoverflow.com/questions/3622590/html-actionlink-with-a-specified-html-id

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You were on the right track. I am not sure why it didn't work for you as your code has a typo which would have produced a } expected error. The following is what you are looking for:

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

Which produces teh following HTML:

<a href="/SomeController/SomeAction" id="someID">Test Link</a>

Edit: I just realized what the issue is because I was mis-reading what you tried. You are using the wrong overload to pass in the id html element. Your probably passing the new { id="blah" } param into the routeValues parameter, which will cause it to be used when building the route link, rather than the htmlAttributes paramater which is what you want.

I think you are using:

ActionLink(string linkText, string actionName, Object routeValues,
    Object htmlAttributes)

When what you need to use is the following overload like I did above in my answer:

ActionLink(string linkText, string actionName, string controllerName,
    Object routeValues, Object htmlAttributes)

Which makes sure new { id="blah" } is being passed into the htmlAttributes param.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...