MVC 5使用@ Url.RouteUrl使用参数进行路由

时间:2015-05-11 10:09:31

标签: asp.net-mvc routing asp.net-mvc-5 asp.net-mvc-routing

我有一个ActionResult,我已将路由属性应用于:

[Route("myproduct/{productID}", Name = "myproduct")]
[MvcSiteMapNode(Title = "Products", ParentKey = "products", Key = "myproducts")]
public ActionResult myproducts(int productID) ...

我试图通过RouteUrl链接到视图:

<a href="@Url.RouteUrl("myproducts", @Model.myproducts[i].productID)">Buy</a>

生成的html甚至不包含href:

<a>Buy</a>

如果我删除了它的工作参数:

[Route("myproducts", Name = "myproducts")]
[MvcSiteMapNode(Title = "Products", ParentKey = "home", Key = "myproducts")]
public ActionResult myproducts(int productID) ...


<a href="/products/myproducts">Book</a>

我是否尝试错误地添加参数?文档提出我正在尝试的内容。

路线配置:

public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapMvcAttributeRoutes();

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );            
    }

2 个答案:

答案 0 :(得分:2)

我可以看到几个问题:

  • 由于您正在将productId直接作为Url.RouteUrl方法的第二个参数传递,因此未正确传递参数。您应该正确传递它(并且要小心,以便它匹配路由中参数的名称),例如使用匿名对象:

    @Url.RouteUrl("myproduct", new { productID = Model.myproducts[i].productID })
    
  • 属性中的路由名称和@Url帮助程序中的名称不同(请参阅 myproduct Vs myproducts ):

    [Route("myproduct/{productID}", Name = "myproduct")]
    @Url.RouteUrl("myproducts", @Model.myproducts[i].productID)
    

答案 1 :(得分:1)

尝试:

You requested 'iPhone 5s (E5723F7E-05AC-4858-9C9F-495C1FA3A00B) (7.1 Simulator)', but the available devices were: ["iPad 2 (8.1 Simulator) [3DD93343-67D4-4EAD-92AA-C005B7933E6D]","iPad Air (8.1 Simulator) [77400AA8-80E0-4ECB-ADCD-08DF3767B57E]","iPad Retina (8.1 Simulator) [A6C0CF5A-255B-4029-AE95-569DA7B29B90]","iPhone 4s (8.1 Simulator) [9CA88BC6-E3ED-44CA-89D8-05487C88A944]","iPhone 5 (8.1 Simulator) [C68E6A43-DBE7-4D85-9CE5-BB87B9915BB0]","iPhone 5s (8.1 Simulator) [E5723F7E-05AC-4858-9C9F-495C1FA3A00B]","iPhone 6 (8.1 Simulator) [4391D23F-BA21-4FB8-8887-0972D2911420]","iPhone 6 Plus (8.1 Simulator) [71B23D13-3F3F-4828-910A-2FAEEABD1C1A]"]

并改变您的行动路线,如:

@Url.RouteUrl("myproducts", new { productID = Model.myproducts[i].productID })