【问题标题】:How to pass a string to my controller action如何将字符串传递给我的控制器操作
【发布时间】:2016-08-22 22:29:04
【问题描述】:

如何映射以下网址...

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

        }

【问题讨论】:

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


    【解决方案1】:

    添加:

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

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

    编辑:应删除或编辑您的实际路线“ProductPages”以避免与我的建议冲突。

    【讨论】:

      【解决方案2】:

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

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

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-06-13
        • 2019-07-02
        • 2018-06-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多