问题背景:
我正在尝试将一个变量 - 在本例中为 url 中的一个 int 'productId' 变量' 传递给 ActionLink 方法中指定的 Controller 和操作方法。
问题:
我的路线设置如下:
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Login", action = "Login", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "ProductDetailHandler",
url: "{controller}/{action}/{productId}",
defaults: new { controller = "Product", action = "ProductDetail", productId = UrlParameter.Optional }
);
我的“Products.cshtml” View 中的“ActionLink”- 由名为“HomePageController”的 Controller 返回,设置如下:
@Html.ActionLink("Product", "ProductDetail", new { productId = (ViewBag.data as List<LoginTest.Models.HomePageItem>).First().Id })
接收传递的“productId”及其操作方法的 Controller 设置如下:
public class ProductController : Controller
{
public ActionResult ProductDetail(int productId)
{
//logic
return View();
}
}
这就是问题所在,在查看 URL 时显示它正在重定向到“主页” Controller :
如果有人能告诉我为什么我的 ActionLink 不转到Product Controller ,那就太好了.
编辑:
这是“主页” View ,我单击一个按钮将我重定向到“product/productDetail/productId”
我的路线现在只有“默认示例”:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Login", action = "Login", id = UrlParameter.Optional }
);
操作链接现在是:
@Html.ActionLink("Product", "ProductDetail", "Product", new { id = (ViewBag.data as List<LoginTest.Models.HomePageItem>).First().Id })
“Product/ProductDetail” Controller 和操作方法现在如下所示:
public class ProductController : Controller
{
public ActionResult ProductDetail(int id)
{
string hold;
return View();
}
}
这仍然给我不正确的 URL,如图所示,请注意“productId”现在显示为“length”?
最佳答案
由于链接位于 HomePageController
呈现的页面上,默认情况下是在路由中使用该 Controller 。您需要使用接受 Controller 名称的重载
@Html.ActionLink("Your link text", "ProductDetail", "Product", new { id = 1 }, null)
作为旁注,您的原始路由表会使用此重载创建 /Product/ProductDetail?productId =1
因为它与默认路由匹配,默认路由是表中的第一条路由(顺序路线很重要)。为了有 /Product/ProductDetail/1
,要么颠倒路由的顺序,要么只是将 ProductDetail
的参数更改为 int id
比 int productId
关于c# - ASP.NET MVC ActionLink 没有选择正确的 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26810692/