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?
From stackoverflow
-
Won't you be able to find the proper Document simply based off its ID?
Won't the Title be redundant?
Mahesh : ID is unique, but title to have better urlKevin Pang : 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. -
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.
-
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)Ray Vernagus : 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.eu-ge-ne : Thanks Ray - you are right. It was a typo. I'll update my answer
0 comments:
Post a Comment