views:

358

answers:

3

I have the following route definition in a MapRoute Table:

routes.MapRoute(
            "ViewDocument",
            "browse/document/{document_id}/{document_title}",
            new { controller = "Document", action = "ViewDocument"}
            );

I have to create links of documents on document index view (document object have "id" and "title" property)

What should be my approach to generating the link in ASP.NET MVC?

Is there anything I am doing wrong with the route definition?

A: 

Won't you be able to find the proper Document simply based off its ID?

Won't the Title be redundant?

Jack Marchetti
ID is unique, but title to have better url
Mahesh
StackOverflow question urls do the same thing. The title is often redundant, but useful for people who want to have a vague idea of what they're clicking on before visiting the link. It's also useful for SEO.
Kevin Pang
A: 

You can generate links to documents for the route given with the following:

<%= Html.ActionLink("Doc Link", "Title", "Document", new { document_id="id", document_title="title" }, null) %>

A couple of things to be aware of:

  • Your custom route must be added before the Default route.
  • You have to include the route values as shown above in order to have them specified in the link.
Ray Vernagus
+3  A: 

In your routes:

routes.MapRoute(
    "ViewDocument",
    "browse/document/{document_id}/{document_title}",
    new { controller = "Document", action = "Title", document_id = "", document_title = ""}
);

In your View:

<%= Url.RouteUrl("ViewDocument", new { document_id = ... , document_title = ... }) %>

(renders plain url)

or

<%= Html.RouteLink("ViewDocument", new { document_id = ... , document_title = ... }) %>

(renders <a></a> element with href attribure filled with the url)

eu-ge-ne
Url.RouteUrl does not create an HTML anchor element. You will either have to hand write the link and use Url.RouteUrl for the href or use Html.ActionLink as I suggested.
Ray Vernagus
Thanks Ray - you are right. It was a typo. I'll update my answer
eu-ge-ne