【问题标题】:How can I configure ASP.NET MVC routing in C#?如何在 C# 中配置 ASP.NET MVC 路由?
【发布时间】:2020-04-21 07:16:09
【问题描述】:

有一个关于 ASP.NET MVC 中路由的问题。

我想在我的应用中拥有漂亮的 URL,这就是我使用路由的原因

context.MapRoute(
     name: "ManageProducts_Home",
     url: "Eshop/ManageProducts/{eshopId}",
     defaults: new { controller = "ManageProducts", action = "Home", AreaName = "Eshop" }
);

这给了我很好的网址,比如

https://localhost:44381/Eshop/ManageProducts/22

太棒了!

那我还有一条路线:

context.MapRoute(
     name: "ManageProducts_AddProduct",
     url: "Eshop/ManageProducts/AddProduct/{eshopId}/{topCategoryId}",
     defaults: new { controller = "ManageProducts", action = "AddProduct", AreaName =  "Eshop" }
);

生成此 URL:

https://localhost:44381/Eshop/ManageProducts/AddProduct/22/1

好的,到目前为止一切顺利。

但是在第二页 (AddProduct) 上,我需要通过 AJAX 刷新一些局部视图,我这样称呼它

$("._SelectCategory").load("/Eshop/ManageProducts/_SelectCategory", { categoryId: categoryId });

控制器中当然有一个动作_SelectCategory,它接受一个参数categoryId

问题是,这个调用被第一个路由捕获并且失败,异常缺少eshopId in action Home,这意味着这个调用不会去我那里的默认路由

context.MapRoute(
     "Eshop_default",
     "Eshop/{controller}/{action}/{id}",
     new { action = "Index", id = UrlParameter.Optional }
);

我需要一些建议,如何在视图 AddProduct 中配置路由,以进行 ajax 调用。

谢谢

【问题讨论】:

    标签: c# asp.net-mvc routing


    【解决方案1】:

    使用 Web API 空控制器并在那里提供更高效的路由 例如: 在 ManageProducts 控制器中

    [HttpGet]
    [Route("api/Eshop/ManageProducts/{eshopId}")]
    

    在您的 Startup.cs 中配置肉类 添加这个:app.UseMvc();

    【讨论】:

      猜你喜欢
      • 2017-07-12
      • 2021-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-09
      • 1970-01-01
      • 1970-01-01
      • 2014-12-01
      相关资源
      最近更新 更多