[英]How can I do route configuration in ASP.NET MVC?
How can I do route configuration as below?如何进行如下路由配置?
My current url is: http://localhost:4815/Home/ByCategory/1
我当前的网址是:
http://localhost:4815/Home/ByCategory/1
But I want it to be: http://localhost:4815/CategoryTitle
但我希望它是:
http://localhost:4815/CategoryTitle
public ActionResult ByCategory(int? id)
{
...
}
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "ByCategory", id = UrlParameter.Optional }
);
You can use Attribute Routing
.您可以使用
Attribute Routing
。 for doing this at first you must Enable it by adding below code top of your MapRoute
in RouteConfig
:首先要执行此操作,您必须通过在
RouteConfig
中的MapRoute
顶部添加以下代码来启用它:
routes.MapMvcAttributeRoutes(); //Enables Attribute Routing
then you can add Attribute Routing
at top of your classes and methods:然后你可以在你的类和方法的顶部添加
Attribute Routing
:
[Route("CategoryTitle")]
public ActionResult ByCategory(int? id)
{
...
}
for deep dive in Routing
, you can follow this link .要深入了解
Routing
,您可以点击此链接。
good luck.祝你好运。
If you want to parametrize a route with Category Title, you can use Attribute Routing like so如果要使用类别标题参数化路由,可以像这样使用属性路由
[Route("~/{categoryTitle}")]
public ActionResult ByCategory(string categoryTitle)
...
Thank you for your suggestions.谢谢你的建议。 I have added the following code to routeconfig.
我已将以下代码添加到 routeconfig。 I used
<a href="/question"> </a>
on the view page to go to the relevant controller我在视图页面上使用了
<a href="/question"> </a>
去相关的控制器
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "AddQuestion",
url: "AddQuestion",
defaults: new { controller = "Question", action = "Create" }
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.