views:

44

answers:

2

Hi there, quick question...

How can I best create internal links? This is the markup I want to achieve:

<h3>Title</h3>
<ul>
  <li><a href="#prod1">Product 1</li>
  <li><a href="#prod2">Product 2</li>
  <li><a href="#prod3">Product 3</li>
  ...
  <li><a href="#prod100">Product 100</li>
</ul>

<div id="prod1">
  <!-- content here -->
</div>

Using MVC 2 I'm using, what's the best Html Helper to use?

<h3><%= Html.Encode(Model.Title) %>
<ul>

<% foreach ( var item in Model.Categories ) {%>
    <li><%= Html.RouteLink( item.Description, ???? ) %></li>
<%} %>

</ul>

What's the best way to get a url to an internal link? String.Format a link from scratch? There's gotta be a better way.

+1  A: 

Hello,

<a href="#<%: item.Category %>"></a>

The routing features weren't meant for internal links; you have to generate them yourself.

Brian
`<%:` is Asp.Net 4 syntax. It would be `<%= Html.Encode(item.Category) %>` in 3.5. Thanks for confirming what i suspected, though.
Atømix
<%: is MVC 2 syntax; I did this in VS 2008, .NET 3.5 SP 1. No problem.
Brian
Really? That's strange... I don't remember it working for me. I'm going to have to try it again!
Atømix
Maybe I am thinking VS 2010... I could be mixing it up...
Brian
+1  A: 
public static TagBuilder LocalAnchor(this HtmlHelper helper, string anchor, string text)
{
    var tag = new TagBuilder("a");
    tag.MergeAttribute("href", "#" + anchor);
    tag.SetInnerText(text);
    return tag;
}
Ryan
Innovative solution.
Atømix
I'm assuming you'd use this like so: `Html.LocalLink("anchor","name")` but it returns an error. Please excuse my ignorance when it comes to MVC...
Atømix
What is the error? I didn't have any problem using this with the Spark view engine. Btw, it's **LocalAnchor**.
Ryan
Sorry, I have my other Html Methods returning strings instead of TagBuilders. I changed this one and it seems to work now.
Atømix