MVC链接创建

时间:2011-06-20 19:10:40

标签: c# model-view-controller routes

使用此路线:

    routes.MapRoute(
        "PartListRoute",
        "Products/PartList/{Manufacturer}/{Product}/{PartNumber}",
        new { controller = "PartList", action = "Index", Manufacturer = UrlParameter.Optional, Product = UrlParameter.Optional, PartNumber = "" }
    );

我正在尝试根据从数据库中提取的制造商列表创建从/ Products / PartList到/ Products / PartList / Manufacturer1的链接。 mfr.Name是制造商的名称。

该路线应该像以下

那样引导网址
  • /产品/ PARTLIST /
  • /产品/ PARTLIST / Manufacturer1 /
  • /产品/ PARTLIST / Manuracturer3 /产品1 /
  • /产品/ PARTLIST / Manuracturer2 /产品4 / DN-438

我最接近的是

@Html.RouteLink(mfr.Name, "PartListRoute", new { Manufacturer = mfr.Name} )

将制造商名称放在文本中,但不会将其添加到URL中。我觉得我正在假设一些不正确的路线和链接。

是否真的有办法使用Route以正确的格式生成新链接?

1 个答案:

答案 0 :(得分:0)

如果其他人遇到这个问题,我最后偶然发现了这篇文章,指出当你有连续的可选网址参数时会出现错误。

http://haacked.com/archive/2011/02/20/routing-regression-with-two-consecutive-optional-url-parameters.aspx

我不会声称我完全理解这个解释,但创建指向原始控制器的其他路线似乎已经解决了问题:

        routes.MapRoute(
            "PartListRoute",
            "Products/PartList/{Manufacturer}",
            new { controller = "PartList", action = "Index", Manufacturer = UrlParameter.Optional }
        );

        routes.MapRoute(
            "PartListRoute2",
            "Products/PartList/{Manufacturer}/{Product}",
            new { controller = "PartList", action = "Index", Manufacturer = UrlParameter.Optional, Product = UrlParameter.Optional }
        );

        routes.MapRoute(
            "PartListRoute3",
            "Products/PartList/{Manufacturer}/{Product}/{PartNumber}",
            new { controller = "PartList", action = "Index", Manufacturer = UrlParameter.Optional, Product = UrlParameter.Optional, PartNumber = "" }
        );