Click here to Skip to main content
14,177,305 members
Rate this:
 
Please Sign up or sign in to vote.
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

Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 1

Try adding constraints to your parameters:
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.
   

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

  Print Answers RSS
Top Experts
Last 24hrsThis month


Advertise | Privacy | Cookies | Terms of Service
Web06 | 2.8.190526.1 | Last Updated 26 Feb 2019
Copyright © CodeProject, 1999-2019
All Rights Reserved.
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100