mvc route actionlink url use name instead of id

前端 未结 2 1290
陌清茗
陌清茗 2021-01-06 01:56

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){
<%         


        
相关标签:
2条回答
  • 2021-01-06 02:44

    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/

    0 讨论(0)
  • 2021-01-06 02:57

    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})
    
    0 讨论(0)
提交回复
热议问题