【问题标题】:How do I construct my action method for a specific route Asp.Net MVC如何为特定路由 Asp.Net MVC 构建我的操作方法
【发布时间】:2018-03-16 10:26:55
【问题描述】:
我正在尝试创建两条路线以供使用
www.mysite.com/Rate/Student/Event/123
www.mysite.com/Rate/Teacher/Event/1234
routes.MapRoute(
name: "Rate",
url: "Rate/Student/Event/{id}"
);
routes.MapRoute(
name: "Rate",
url: "Rate/Teacher/Event/{id}"
);
如何构造动作方法?
这是我的速率控制器中的内容
public ActionResult Student(int id)
{
return View();
}
public ActionResult Teacher(int id)
{
return View();
}
【问题讨论】:
标签:
c#
asp.net-mvc
routes
url-routing
asp.net-mvc-routing
【解决方案1】:
您已设置路由以匹配 URL,但尚未告诉 MVC 将请求发送到何处。 MapRoute 使用 路由值 工作,可以默认为特定值或通过 URL 传递。但是,你什么都没做。
注意: controller 和 action 路由值在 MVC 中是必需的。
选项 1:添加默认路由值。
routes.MapRoute(
name: "Rate",
url: "Rate/Student/Event/{id}",
defaults: new { controller = "Rate", action = "Student" }
);
routes.MapRoute(
name: "Rate",
url: "Rate/Teacher/Event/{id}",
defaults: new { controller = "Rate", action = "Teacher" }
);
选项 2:通过 URL 传递路由值。
routes.MapRoute(
name: "Rate",
url: "{controller}/{action}/Event/{id}"
);