views:

91

answers:

3

My original question was a bit confusing, so let me edit this post to be more clear:

How can I generate an ActionLink that not only uses the Routing engine, but also takes you to an html element with particular ID on a page? I want to generate something like this:

<a href="/ControllerName/ActionName/#section2>Link</a>

or sometimes the same but with an action parameter of 15 for example:

<a href="/ControllerName/ActionName/15#section2>Link</a>

Where the View served by the actionName has an element with the id of "section2":

<div id="section1">
  <h1>Section 1</h1>
  ...
</div>
<div id="section2">
  <h1>Section 2</h1>
  ...
</div>

I believe that I could write a Html helper method that uses Url.RouteUrl() and then append the "#sectionId" but is this the easiest/best way to do this? Should I create a routing rule for this? The default route:

routes.MapRoute(
    "Default",
    "{controller}/{action}/{id}",
    new { controller = "Experiment", action = "Index", id = "" }
);

allows me to manually add "#section2" to the end of the url in my browser and it takes me to the section2 div. It seems like rather than adding or changing a route I simply need to append "#section2" to the ActionLink url.

+1  A: 

For the following route:

        routes.MapRoute(
            "Default",
            "{controller}/{action}/{id}/{section}",
            new { controller = "Home", action = "Index", id = "", section = "" }
        );

you would do:

<%= Html.ActionLink("Link Text", "Index", new { section = "#sectionId" }) %>
Mark
That will get me a link to the action, passing in the ID as a parameter, but I want to go one step further and then scroll down to the particular element with the a particular id (say id="sectionId")
sdr
you mean an "anchor" tag then!!! let me edit.
Mark
+2  A: 

You would want to change/add a route to be:

routes.MapRoute("MyRoute", "{controller}/{action}#{id}", /* some default here */);

Then the MVC Helper would be:

<%= Html.ActionLink("Link Text", "Index", new { id = "sectionId" }) %>
mkedobbs
+1  A: 

I think the OP wants the ID to be the anchor ref at the end of the URL, as it appears to be a list of items and he wants the browser to scroll down to the item. (I'm just guesing here because of the "#" stipulation. Small edit to Mark's code:

routes.MapRoute(
  "Default",
  "{controller}/{action}/#{sectionId}",
  new { controller = "Home", action = "Index", sectionId = Model.SectionId } );
Chris Simmons