tags:

views:

4154

answers:

2

In ASP.NET MVC, I'm trying to create a link that includes an anchor tag (i.e., directing the user to a page, and a specific section of the page).

The URL I am trying to create should look like the following:

<a href="/category/subcategory/1#section12">Title for a section on the page</a>

My routing is set up with the standard:

routes.MapRoute("Default", "{controller}/{action}/{categoryid}");

The action link syntax that I am using is:

<%foreach (Category parent in ViewData.Model) { %>
<h3><%=parent.Name %></h3>
<ul>
<%foreach (Category child in parent.SubCategories) { %>
    <li><%=Html.ActionLink<CategoryController>(x => x.Subcategory(parent.ID), child.Name) %></li>
<%} %>
</ul>
<%} %>

My controller method is as follows:

public ActionResult Subcategory(int categoryID)
{
   //return itemList

   return View(itemList);
}

The above correctly returns a URL as follows:

<a href="/category/subcategory/1">Title for a section on the page</a>

What I can't figure out is how to add the #section12 part. The "section" word is just the convention I am using to break up the page sections, and the 12 is the ID of the subcategory, i.e., child.ID.

Any help is appreciated.

+7  A: 

I would probably build the link manually, like this:

<a href="<%=Url.Action("Subcategory", "Category", new { categoryID = parent.ID }) %>#section12">link text</a>
Lck
Should really use the overloads for ActionLink as described by @Brad Wilson.
mattruma
+22  A: 

There are overloads of ActionLink which take a fragment parameter. Passing "section12" as your fragment will get you the behavior you're after.

For example, calling LinkExtensions.ActionLink Method (HtmlHelper, String, String, String, String, String, String, Object, Object):

<%= Html.ActionLink("Link Text", "Action", "Controller", null, null, "section12-the-anchor", new { categoryid = "blah"}, null) %>
Brad Wilson
Are these overloads part of an extensions library? I don't seem to get them.
grenade
There are two: 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);
Brad Wilson
+1 This is definitely the better way.
mattruma