Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mvc route actionlink url use name instead of id

I think I already asked this but the solution didn't really made sense. Anyway, I have ActionLinks on my views like this:

foreach( var item in Model){
<%: Html.ActionLink(item.Name, "Details", new {id = item.Id}) %>
}

now, when it goes to my Action Details obviously this will be the url

/MyThings/Details/{id}

I was wondering if it's possible to show the name of that item instead of the id Using a slug? or modifying the global asax like so:

/MyThings/Details/CarKeys

The thing is the names need to be unique, is there a way I can modify the global asax to show the name instead of the id?

Any advice is much appreciated!

like image 390
gdubs Avatar asked Oct 21 '11 15:10

gdubs


2 Answers

If this is solely for SEO purposes, just include both the ID and the Name. The name will be part of the URL but not used by your application. Just add another route that uses the template: {controller}/{action}/{id}/{name}

You'll also want to transform your name to make sure that it has only valid characters for urls. There are tons of articles about this on the net and it's pretty simple. Here's an example: http://chrismckee.co.uk/creating-url-slugs-permalinks-in-csharp/

like image 54
Malevolence Avatar answered Nov 07 '22 14:11

Malevolence


Sure, you just have to change your routing rules. Look in your Global.asax.cs file, or in your area registration file, for something like this:

routes.MapRoute(..., "{controller}/{action}/{id}", ...);

... and change it to something like this:

routes.MapRoute(..., "{controller}/{action}/{name}", ...);

Then have your action take the name instead of the ID:

Html.ActionLink(item.Name, "Details", new {item.Name})
like image 43
StriplingWarrior Avatar answered Nov 07 '22 14:11

StriplingWarrior