【问题标题】:Can't map route to action mvc3无法将路线映射到动作 mvc3
【发布时间】:2013-05-30 17:16:33
【问题描述】:

我正在尝试在MVC3中创建一个新的Route来实现链接http://localhost/Product/1/abcxyz

routes.MapRoute(
                "ProductIndex", // Route name
                "{controller}/{id}/{name}", // URL with parameters
                new { controller = "Product", action = "Index", id = UrlParameter.Optional, name = UrlParameter.Optional } // Parameter defaults
            );

我这样使用Route Link

<li>@Html.RouteLink("My Link", "ProductIndex", new { controller = "Product", id = 10, name = "abcxyz" })</li>

产品索引操作:

public ViewResult Index(int id, string name)
        {
            var product = db.Product.Include(t => t.SubCategory).Where(s => s.SubID == id);
            return View(product.ToList());
        }

网址按我的预期呈现。但是当我点击它时,我收到了一个带有消息的 404 错误

HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable.  Please review the following URL and make sure that it is spelled correctly

更新

我将 Route 放在 Default Route 上方,并且 URL 工作正常。但是出现了问题。我的索引页面http://locahost 直接指向Product 控制器的Index 操作,但我希望它指向Home 控制器的Index 操作

【问题讨论】:

    标签: asp.net-mvc-3


    【解决方案1】:

    这是因为您的路线中有 2 个可选参数,并且引擎无法确定将值设置为哪一个。查看我对类似问题的回答here

    您可以先为您的产品控制器创建一个特定的路由(带有强制 id),然后再创建通用的后备路由。

    routes.MapRoute(
                "ProductIndex", // Route name
                "products/{id}/{name}", // URL with parameters
                new { controller = "Product", action = "Index", name = UrlParameter.Optional } // Parameter defaults
            );
    

    【讨论】:

    • 非常好,先生。你救了我一天。
    【解决方案2】:

    试试看

    routes.MapRoute(
                    "Default", // Route name
                    "{controller}/{id}/{name}", // URL with parameters
                    new { controller = "Home", action = "Index", id = UrlParameter.Optional, name = UrlParameter.Optional } // Parameter defaults
                );
    

    有关路由的详细信息,请参阅此链接。在此链接中讨论了每种类型的路由。

    http://www.codeproject.com/Articles/408227/Routing-in-MVC3

    【讨论】:

    • 这将适用于所有路线。但我只希望它只适用于Product 控制器的Index 动作。
    • @Atish Dipongkor 感谢您的关注,我在上面找到了 leveInis 答案的解决方案
    猜你喜欢
    • 2012-05-30
    • 1970-01-01
    • 2014-04-18
    • 2011-08-21
    • 1970-01-01
    • 1970-01-01
    • 2016-05-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多