如何将字符串传递给我的控制器操作

时间:2016-08-22 22:29:04

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

如何映射以下网址...

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

        }

2 个答案:

答案 0 :(得分:1)

添加:

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

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

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

答案 1 :(得分:0)

此代码实际上并未调用操作:

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 }
            );
相关问题