mvc route actionlink url use name instead of id

2019-02-14 00:43发布

问题:

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!

回答1:

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})


回答2:

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/