如何传递字符串到我的控制器动作

本文关键字:控制器 我的 何传递 字符串 | 更新日期: 2023-09-27 18:03:34

如何映射以下url…

domain.com/Products/product-name-here

我想把它映射到我的产品控制器上的GetProduct动作。

下面是我在route.config

中的配置
   public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
            routes.MapRoute(
                name: "Product",
                url: "product/{id}"
            );
            routes.MapRoute(
                name: "EditProduct",
                url:"Admin/Product/{action}",
                defaults: new { controller = "Products", action = "Index"}
            );
            routes.MapRoute(
                name:"ProductPages",
                url:"Products/{id}",
                defaults: new {controller = "Products", action = "GetProduct", id = UrlParameter.Optional }
            );
            routes.MapRoute(
                name:"OrderRoute",
                url:"Orders/",
                defaults: new { controller= "Order", action="Index"}
                );
        }

这是我想要映射到的动作

[HttpGet]
        public ActionResult GetProduct(string pageURL)
        {
            if ( string.IsNullOrWhiteSpace(pageURL))            
                            return View("PageNotFound");

            var product = db.Products.Where(x => x.PageURL == pageURL);
            return View("GetProduct");
        }

如何传递字符串到我的控制器动作

添加:

routes.MapRoute(
    name:"ProductPages",
    url:"Products/{pageURL}",
    defaults: new {controller = "Products", action = "GetProduct" }
);

重要:你的默认路由应该是route.config中的最后一条路由。在你的代码中,它是第一个。

编辑:你的实际路由"ProductPages"应该被删除或编辑,以避免与我的建议冲突。

这段代码实际上并没有调用一个动作:

routes.MapRoute(
                name:"ProductPages",
                url:"Products/{id}",
                defaults: new {controller = "Products", action = "GetProduct", id = UrlParameter.Optional }
            );

你想添加一个使用如下动作的路由(注意action标签):

routes.MapRoute(
                name:"ProductPages",
                url:"Products/{action}/{id}",
                defaults: new {controller = "Products", action = "GetProduct", id = UrlParameter.Optional }
            );