Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC 4 creating slug type url

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://localhost:12719/Thread/Thread/500/slug-url-text

Note the first Thread is the controller the second is the action.

How can i make the above URL look like the following excluding the controller name from the url?

 http://localhost:12719/Thread/500/slug-url-text

My Routes

   public class RouteConfig
   {
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute("Default", // Route name
             "{controller}/{action}/{id}/{ignoreThisBit}",
             new
             {
                 controller = "Home",
                 action = "Index",
                 id = "",
                 ignoreThisBit = ""
             });  // Parameter defaults )


    }
 }

Thread Controller

 public class ThreadController : Controller
 {
    //
    // GET: /Thread/

    public ActionResult Index()
    {

        string s = URLFriendly("slug-url-text");
        string url = "Thread/" + 500 + "/" + s;
        return RedirectPermanent(url);

    }

    public ActionResult Thread(int id, string slug)
    {

        return View("Index");
    }

}

like image 397
Raju Kumar Avatar asked Apr 27 '13 05:04

Raju Kumar


1 Answers

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.

like image 171
shakib Avatar answered Sep 20 '22 13:09

shakib