问题
I have an ActionResult that I have applied a routing attribute to:
[Route("myproduct/{productID}", Name = "myproduct")]
[MvcSiteMapNode(Title = "Products", ParentKey = "products", Key = "myproducts")]
public ActionResult myproducts(int productID) ...
I am trying to link to the view via a RouteUrl:
<a href="@Url.RouteUrl("myproducts", @Model.myproducts[i].productID)">Buy</a>
The resulting html does not even include a href:
<a>Buy</a>
If I remove the parameter it works:
[Route("myproducts", Name = "myproducts")]
[MvcSiteMapNode(Title = "Products", ParentKey = "home", Key = "myproducts")]
public ActionResult myproducts(int productID) ...
<a href="/products/myproducts">Book</a>
Am I trying to add the parameter incorrectly? The documentation suggests what I am attempting.
Route Config:
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 }
);
}
回答1:
Try:
@Url.RouteUrl("myproducts", new { productID = Model.myproducts[i].productID })
And change your action route like:
[Route("myproducts/{productID}", Name = "myproducts")]
[MvcSiteMapNode(Title = "Products", ParentKey = "home", Key = "myproducts")]
public ActionResult myproducts(int productID) {
}
回答2:
I can see a couple of issues:
The parameter is not being passed correctly, as you are passing the productId directly as the second parameter of the Url.RouteUrl method. You should pass it correctly (and be careful so it matches the name of the parameter in the route), for example using an anonymous object:
@Url.RouteUrl("myproduct", new { productID = Model.myproducts[i].productID })
The name of the route in the attribute and the name in the @Url helper are different (See myproduct Vs myproducts):
[Route("myproduct/{productID}", Name = "myproduct")] @Url.RouteUrl("myproducts", @Model.myproducts[i].productID)
来源:https://stackoverflow.com/questions/30164896/mvc-5-routing-with-parameter-using-url-routeurl