简体   繁体   中英

Configuring my route in Asp.Net MVC

I'm trying to configure my route so that it reflects the tab the user is on within the page. Pics below. If the state is on 'Upcoming' I want to just have a route with the state = Upcoming like this with no month or year

www.mysite.com/Schedule/Host/Upcoming

if the state is 'Past' I need to require a month and year like this

www.mysite.com/Schedule/Host/Past/March/2016

The problem is that I can enter in just the controller and action

Schedule/Host

and the route gets through to the action method. I want to prevent this.

here are some examples

www.mysite.com/Schedule/Host -> no pass with just the controller and action

www.mysite.com/Schedule/Host/Upcoming -> ok with no month or year

www.mysite.com/Schedule/Host/Past/March/2016 -> when state = past you must provide a month and year

Here is what the page will look like with Upcoming as the state

https://localhost:44368/Schedule/Host/Upcoming

在此处输入图片说明

Here is what it will look like with past as the state

https://localhost:44368/Schedule/Host/Past/March/2017

在此处输入图片说明

Here is my routing

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

        routes.MapRoute(
            name: "ScheduleByState",
            url: "{controller}/{action}/{state}/{month}/{year}",
            defaults: new { month = UrlParameter.Optional, year = UrlParameter.Optional}
        );

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


    }

Here is my action method Host

public ActionResult Host(string state, string month, string year)
{
    ViewBag.MenuItem = "schedule";
    ViewBag.UserMenuItem = "host";
    return View();
}

not sure if i understand your question correctly

but seems you have to set multiple routes to satisfy your requirement

routes.MapRoute(
            name: "home",
            url: "{controller}/{action}/"
            }
        );    

routes.MapRoute(
            name: "ScheduleByState",
            url: "{controller}/{action}/Upcoming/"
           }
        );


routes.MapRoute(
            name: "ScheduleByState",
            url: "{controller}/{action}/Past/{month}/{year}"
           }
        );

another solution is use regex in your router parameter, it will make things more complicated, so if you have only these fixed states, probably more rules will be easier to handle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM