regexasp.net-mvc-5asp.net-mvc-routingdynamic-pages

asp.net mvc route constraints regular expression


I want to server dynamic pages using url without controller and action on the basis of page title
default url : domain.com/pages/details/1
I want this to be server as
domain.com/title-of-dynamic-page-in-db-space-replaced-with-dash
domain.com/about-us
domain.com/contact-us

if I am doing this without dash than routing will confuse with controller name
thats why I added dash - for dynamic pages

my action looks like this

    // GET: Pages/View/5
    public ActionResult View(string id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Page page = db.Pages.First(p => p.name_english == id.Replace("-"," "));
        if (page == null)
        {
            return HttpNotFound();
        }
    }

my routes are

        routes.MapRoute(
            name: "aaaaa",
            url: "{id}",
            defaults: new { controller = "pages", action = "view" },
            constraints: new { id = @"^[A-Za-z\d-]+$" } //*********help needed in this line ******************************
        );


        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );

above Constrain ^[A-Za-z\d-]+$
accepts alpha(optional) numeric(optional) and dash(optional)

while I need alpha(optional) numeric(optional) and dash(*mandatory*)

this way routing engine will not confuse page title with controller/action as I will make sure my name of dynamic page will contain space(i m replacing with dash)
and my controller/action will not be named contained dash

also tell me, is this approach ok or not, is there any other optimized solution for this?


Solution

  • I hope the following snippet will work for you.

        routes.MapRoute(
            name: "aaaaa",
            url: "{id}",
            defaults: new { controller = "pages", action = "view" },
            constraints: new { id = @"^([-]*[a-zA-Z0-9]*-[a-zA-Z0-9]*[-]*)+$" } //*********this should work**
        );
    
        //---------------------------------------
        // ^([-]*[a-zA-Z0-9]*-[a-zA-Z0-9]*[-]*)+$
        //---------------------------------------