Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a URL Fragment to an MVC ActionLink

Tags:

c#

asp.net-mvc

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?

like image 630
Luke101 Avatar asked Jan 03 '10 20:01

Luke101


People also ask

What is difference between HTML ActionLink and URL action?

Yes, there is a difference. Html. ActionLink generates an <a href=".."></a> tag whereas Url. Action returns only an url.

How can create href link in ASP NET MVC?

The Anchor Tag Helper generates HTML anchor (<a> </a>) element by adding a new attribute. The "href" attribute of the anchor tag is created by using new attributes. The Anchor Tag Helper generates an HTML anchor (<a> </a>) element by adding new attribute.

What is HTML ActionLink in MVC?

Html. ActionLink creates a hyperlink on a view page and the user clicks it to navigate to a new URL. It does not link to a view directly, rather it links to a controller's action.

How do you pass an ActionLink model?

ActionLink is rendered as an HTML Anchor Tag (HyperLink) and hence it produces a GET request to the Controller's Action method which cannot be used to send Model data (object). Hence in order to pass (send) Model data (object) from View to Controller using @Html.


2 Answers

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.

like image 183
Eilon Avatar answered Nov 09 '22 05:11

Eilon


You need to call this overload

like image 2
SLaks Avatar answered Nov 09 '22 05:11

SLaks