如何为特定路径Asp.Net MVC构建我的操作方法

时间:2017-10-04 21:58:27

标签: c# asp.net-mvc routes url-routing asp.net-mvc-routing

我有两条路线,我正在尝试创建使用

  

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}"
);

如何构建动作方法?

以下是我在Rate控制器中的内容

public ActionResult Student(int id)
{
    return View();
}

public ActionResult Teacher(int id)
{
    return View();
}

1 个答案:

答案 0 :(得分:4)

您已设置路由以匹配该网址,但您尚未告知MVC将请求发送到何处。 MapRoute使用路由值工作,可以默认为特定值或通过URL传递。但是,你们两个都没做。

  

注意: MVC中需要controlleraction路由值。

选项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}"
    );