4

I need razor to generate a href links. This code works fine:

@Html.ActionLink("Questions", "Questions", "SectionPartials")

How do I set an id element to the a href tag? I already tried:

@Html.ActionLink("Questions", "Questions", "SectionPartials", new { id= "new-link" })

Which adds a id to the a href, but the navigations won't work anymore. This also gives a error in the code (but does compile tho)

Server error: enter image description here

Code error enter image description here

Coudn't find any more information on this issue.. If there is some information missing (like controller/view(?)), I am happy to add those!

Thanks

Jim Vercoelen
  • 1,048
  • 2
  • 14
  • 40
  • You need to add a null parameter before your `new { id = "new-link" }` parameter, as you can see in Intellisense. – ragerory Dec 01 '15 at 20:10
  • 1
    its weird when you say that you could not find any solution for this question.. [this](http://stackoverflow.com/questions/8293934/passing-parameter-to-controller-action-from-a-html-actionlink) , [this](http://stackoverflow.com/questions/14152575/pass-parameter-to-controller-from-html-actionlink-mvc-4) and there are many more. All this i got with a Google search.. – Vini Dec 02 '15 at 06:36
  • @Vini I apologize for not good search, I think because I am new on ASP.NET so I didn't know how to search more than I did – Jim Vercoelen Dec 02 '15 at 16:52
  • Being new to a technology doesnt have anything to do with searching. Anyways you got an answer. So no issues – Vini Dec 02 '15 at 16:55

2 Answers2

6

The desired LinkExtensions.ActionLink method signature is:

public static MvcHtmlString ActionLink( this HtmlHelper htmlHelper, string linkText, string actionName, object routeValues, object htmlAttributes )

So, your current new { id= "new-link" } is passed as the routeValues parameter. You need to pass it as the htmlAttributes instead:

@Html.ActionLink("Questions", "Questions", "SectionPartials", null, new { id= "new-link" });

Or (using named parameters):

@Html.ActionLink("Questions", "Questions", "SectionPartials", htmlAttributes: new { id= "new-link" });

See MSDN

haim770
  • 48,394
  • 7
  • 105
  • 133
  • 1
    Hey Thanks for response, answer already was given but the extra explanation is really userfull!! (cant approve for 8 min, i will approve this one in a couple of minutes)! – Jim Vercoelen Dec 01 '15 at 20:13
3

Try this because you need to ignore routeValues if you don't have some additional parameters:

@Html.ActionLink("Questions", "Questions", "SectionPartials", null, new { id= "new-link" })

or:

@Html.ActionLink("Questions", "Questions", "SectionPartials",  htmlAttributes : new { id= "new-link" })
TotPeRo
  • 6,561
  • 4
  • 47
  • 60