c# - ASP.NET MVC ActionLink 没有选择正确的 Controller

标签 c# asp.net-mvc asp.net-mvc-4 routes

问题背景:

我正在尝试将一个变量 - 在本例中为 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

enter image description here

我的路线现在只有“默认示例”:

 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”?

enter image description here

最佳答案

由于链接位于 HomePageController 呈现的页面上,默认情况下是在路由中使用该 Controller 。您需要使用接受 Controller 名称的重载

@Html.ActionLink("Your link text", "ProductDetail", "Product", new { id = 1 }, null)

作为旁注,您的原始路由表会使用此重载创建 /Product/ProductDetail?productId =1 因为它与默认路由匹配,默认路由是表中的第一条路由(顺序路线很重要)。为了有 /Product/ProductDetail/1,要么颠倒路由的顺序,要么只是将 ProductDetail 的参数更改为 int idint productId

关于c# - ASP.NET MVC ActionLink 没有选择正确的 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26810692/

相关文章:

c# - 从 MVC 4 Web Api 返回匿名类型失败并出现序列化错误

asp.net-mvc-4 - 我什么时候需要在 RouteConfig.cs ASP.Net MVC 中注册路由?

c# - 如何确定哪个参数集导致测试失败?

c# - 关于封装的概念

asp.net-mvc - 如何突出显示 DevExpress MVC GridView 页面中的特定行?

asp.net-mvc - 带有数据注释的 KendoUI 网格默认值

javascript - 在剑道网格中从 ajax 呈现数据时如何显示微调器

c# - 如何强制文档评论

c# - 如何将 DataSource 设置为 DropDownList?

asp.net-mvc - Html.BeginForm 使用 FormMethod.GET 丢失了 RouteValues