Click here to Skip to main content
15,885,767 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi,

Need help to know if this is possible in ASP.Net MVC5

I want to set up routing such that

1. www.myWebsite.com points to Home/Index and
2. www.myWebsite.com/2/3 points to Chapter/Index

I have a HomeController with a parameterless Index action (which works fine with the default route config) and
I have a ChapterController with 2 parameters whose values must be fed in from the URL (e.g.: 2 & 3 from the sample URL above)

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


My chapter controller is as below
public class ChapterController : Controller
{
        public ActionResult Index(short? chapterID, short? verseNumber)
        {

            ViewModel vm = new ViewModel();
            vm.message = $"chapter: {chapterID} & verse: {verseNumber}";
            return View(vm);
        }
}


What I have tried:

tried to add a MapRoute entry as below but it doesnt work :(
routes.MapRoute(
    name: "Chapter",
    url: "{chapterID}/{verseNumber}",
    defaults: new { controller = "Chapter", action = "Index", verseNumber = UrlParameter.Optional }
);
Posted
Updated 26-Feb-19 7:26am

1 solution

Try adding constraints to your parameters:
C#
routes.MapRoute(
    name: "Chapter",
    url: "{chapterID}/{verseNumber}",
    defaults: new { controller = "Chapter", action = "Index", verseNumber = UrlParameter.Optional },
    constraints: new { chapterID = @"\d+", verseNumber = @"\d*" }
);

Make sure this appears before the default route.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900