Search code examples
c#asp.net-mvcasp.net-mvc-routing

Create Custom Route in MVC 5 for Date


I am trying to convert the below url

https://localhost:44322/BankHoliday/NewBankHoliday?holidayDate=08%2F25%2F2016%2000%3A00%3A00&countryID=GBR

to https://localhost:44322/BankHoliday/NewBankHoliday/holidayDate/08-25-2016/countryID/GBR

I have tried this code but it does not work

 routes.MapRoute(
                null,
                "{holidayDate}/{countryID}",
                new { Controller = "BankHoliday", action = "NewBankHoliday" }, new { holidayDate = @"\d{2}-\d{2}-\d{4}" }
            );

Solution

  • To achieve a url of BankHoliday/NewBankHoliday/holidayDate/08-25-2016/countryID/GBR, you route definition would need to be

    routes.MapRoute(
        name: "Bank",
        url: "BankHoliday/NewBankHoliday/holidayDate/{holidayDate}/countryID/{countryID}",
        defaults: new { controller = "BankHoliday", action = "NewBankHoliday"}
    );
    

    and located before the default route. It unclear why you want the text holidayDate and countryID in the route and a more conventional url would be

    url: "BankHoliday/NewBankHoliday/{holidayDate}/{countryID}",
    

    to generate BankHoliday/NewBankHoliday/08-25-2016/GBR

    Then the controller method will need to be

    public class BankHolidayController : Controller
    {
        public ActionResult NewBankHoliday(DateTime holidayDate, string countryID)
        {
            ....
    

    assuming the culture on your server accepts dates in MM-dd-yyyy format.

    and to generate the link in the view

    @Html.ActionLink("Your Link Text", "NewBankHoliday", "BankHoliday", new { holidayDate = "08-25-2016", countryID = "GBD"}, null)