Greetings. How can I make access to my article or post by their name? For example: Like at stackoverflow has access to this question by the name http://stackoverflow.com/questions/3079363/access-to-article-by-article-name-in-asp-net-mvc2
On StackOverflow the name
part is completely ignored. It's the id that is important. This works: http://stackoverflow.com/questions/3079363/blabla and links to this question. To generate links that contain the name
in the URL you could define the following route:
routes.MapRoute(
"NameIdRoute",
"{controller}/{action}/{id}/{name}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional, name = UrlParameter.Optional },
new { id = @"\d+" }
);
And then:
<%: Html.ActionLink("some text", "action", new { id = Model.Id, name = Model.Name }) %>
Create a route that allows the name to be specified as part of the url. Note that it's probably not actually used in resolving the article as it might not be unique. The id is the bit of information that is actually used to find and display the correct article, but the name is part of the url for context.
routes.MapRoute(
"Question",
"{controller}/{id}/{name}",
new { controller = "questions", action = "show", id = UrlParameter.Optional, name = UrlParameter.Optional },
new { id = "[0-9]+" } // constraint to force id to be numeric
);
Now, when you use Html.ActionLink() and specify the name as a parameter, the route will match and put in the name as a component of the url instead of a query parameter.
<%= Html.ActionLink( "questions", new { id = Model.ID, name = Model.NameForUrl } ) %>
Note that if you have multiple routes that might match you may need to use RouteLink and specify the route by name. Also, order matters.