【问题标题】:ASP MVC 5 Route MappingASP MVC 5 路由映射
【发布时间】:2018-04-14 19:03:01
【问题描述】:

在我的视图文件夹中,我有一个“用户”文件夹,它不包含相应的视图,但包含将包含视图的子文件夹。

例子:

User
 Create
   create.cshtml
 Edit
   edit.cshtml

然后我有一个控制器,目前只有一个用于创建的操作:

public ActionResult Create() {
    return View("Create/Create");
}

所以要执行该操作,我会转到 user/create,然后返回视图正常。

当我尝试使用Url.RouteUrl<a> 标记中链接到该视图时,问题就出现了。它出错并说:

在路由集合中找不到名为“user/create”的路由

但对我来说,它匹配路由配置中的默认路由:controller/action

这是我的 RouteConfig:

public static void RegisterRoutes(RouteCollection routes) {
  routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

  // Turn on attribute routing in the controllers
  routes.MapMvcAttributeRoutes();

  routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new {
      controller = "Home", action = "Index", id = UrlParameter.Optional
    }
  );
}

那么为什么我需要为它定义一个自定义路由呢?

【问题讨论】:

    标签: c# asp.net .net asp.net-mvc


    【解决方案1】:

    您不需要为其定义自定义路由,但您需要遵循文件夹的约定。将 create.cshtml 和 edit.cshtml 视图直接放在 User 文件夹中,并删除 Create 和 Edit 子文件夹,您不需要它们。

    现在,在控制器中,您可以简单地使用:

    public ActionResult Create() {
        return View();
    }
    

    它知道要查找什么以及在哪里找到它,因此它会成功选择您的 User/create.cshtml 视图。但是,我们通常将模型传递给我们的视图。在像 Create 这样的视图中,模型用于构建所有控件(文本框、标签等):

    public ActionResult Create() {
        var model = new UserViewMode();
        return View(model);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多