Mahesh
Mahesh

Reputation: 1784

Generate links in ASP.NET MVC?

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?

Upvotes: 4

Views: 7149

Answers (3)

eu-ge-ne
eu-ge-ne

Reputation: 28153

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)

Upvotes: 6

Ray Vernagus
Ray Vernagus

Reputation: 6150

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.

Upvotes: 0

Jack Marchetti
Jack Marchetti

Reputation: 15754

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

Won't the Title be redundant?

Upvotes: 0

Related Questions