Luke101
Luke101

Reputation: 65248

Adding a URL Fragment to an MVC ActionLink

here is part of my code

this

<%= Html.ActionLink(Model[x].Title, "Index", "q", new { slug = Model[x].TitleSlug, id = Model[x].PostID }, null)%>

produces this url

http://localhost:61158/q/is_there_another_indiana_jones_movie_in_the_works/4

but I want to produce a url with a fragment, like this:

http://localhost:61158/q/is_there_another_indiana_jones_movie_in_the_works/4#1

Is there a way to do this using the HTML.ActionLink function?

Upvotes: 16

Views: 5462

Answers (3)

Fragments are supported in MVC 5. (See https://msdn.microsoft.com/en-us/library/dd460522(v=vs.118).aspx and https://msdn.microsoft.com/en-us/library/dd492938(v=vs.118).aspx.) So your code would be

Html.ActionLink(Model[x].Title, "Index", "q", new { slug = Model[x].TitleSlug, id = Model[x].PostID }, null, "1", null, null)

Upvotes: 0

SLaks
SLaks

Reputation: 887453

You need to call this overload

Upvotes: 2

Eilon
Eilon

Reputation: 25704

There are two "mega overloads" of ActionLink that take a fragment parameter:

public static string ActionLink(this HtmlHelper htmlHelper,
     string linkText, string actionName, string controllerName,
     string protocol, string hostName, string fragment, object routeValues,
     object htmlAttributes);
public static string ActionLink(this HtmlHelper htmlHelper,
     string linkText, string actionName, string controllerName,
     string protocol, string hostName, string fragment,
     RouteValueDictionary routeValues, IDictionary<string, object> htmlAttributes);

See MSDN for more info on the overloads.

In your case it would be (and note the "fragment" parameter in particular):

<%= Html.ActionLink(Model[x].Title, "Index", "q",
     /* protocol */ null, /* hostName */ null, /* fragment */ "1",
     new { slug = Model[x].TitleSlug, id = Model[x].PostID }, null) %>

With the "mega overloads" you can leave most parameter values as null and they will get the appropriate default values.

Upvotes: 24

Related Questions