MVC 4 creating slug type url

后端 未结 1 730
悲哀的现实
悲哀的现实 2020-12-09 00:41

i am trying to create a stackoverflow like url.

I the following example works fine. But if i remove the controller then it errors out.

http://localho         


        
相关标签:
1条回答
  • 2020-12-09 01:18

    Placing the following route before the default route definition will directly call the 'Thread' action in 'Thread' controller with the 'id' and 'slug' parameter.

    routes.MapRoute(
        name: "Thread",
        url: "Thread/{id}/{slug}",
        defaults: new { controller = "Thread", action = "Thread", slug = UrlParameter.Optional },
        constraints: new { id = @"\d+" }
    );
    

    Then if you really want it to be like stackoverflow, and assume someone enters the id part and not the slug part,

    public ActionResult Thread(int id, string slug)
    {
        if(string.IsNullOrEmpty(slug)){
             slug = //Get the slug value from db with the given id
             return RedirectToRoute("Thread", new {id = id, slug = slug});
        }
        return View();
    }
    

    hope this helps.

    0 讨论(0)
提交回复
热议问题