如何根据参数在MVC中为不同的控制器设置路由 [英] How do I set up routing in MVC for different controllers based on parameters
问题描述
在ASP.Net MVC5中需要帮助才能知道这是否可行
我想设置路由,以便
1。 www.myWebsite.com 指向主页/索引和
2。 www.myWebsite.com/2/3 指向章节/索引
我有一个带无参数索引动作的HomeController (使用默认路由配置工作正常)和
我有一个带有2个参数的ChapterController,其值必须从URL输入(例如:上面示例URL中的2& 3) />
我目前的路由如下
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);
}
}
我的尝试:
试图添加一个MapRoute条目如下,但它不起作用:(
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 }
);
推荐答案
章节:{chapterID}& verse:{verseNumber};
返回查看(vm);
}
}
"chapter: {chapterID} & verse: {verseNumber}"; return View(vm); } }
我尝试了什么:
试图添加一个MapRoute条目如下,但它不起作用:(
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 }
);
尝试为参数添加约束:
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.
这篇关于如何根据参数在MVC中为不同的控制器设置路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!