【问题标题】:MVC action method not triggered未触发 MVC 操作方法
【发布时间】:2018-08-29 11:02:47
【问题描述】:

我有一个 MVC5 库存 Web 应用程序,其中包含项目列表和每个项目的交付按钮。

@foreach (var i in Model.Inventario)
{
    @using (Html.BeginForm("AggiungiAlloScarico", "Scarico"))
    {
        string Disabilitato = "";
        string Classe = "";
        // some method to define the buttons' styles

        <div class="pull-right">
            @Html.Hidden("Modello", i.Item.Modello)
            @Html.Hidden("returnUrl", Request.Url.PathAndQuery)
            <input type="submit" class="@(String.Format("{0}", Classe))" value="Consegna" @Disabilitato />
        </div>
    }
}

点击任何这些按钮时,Scarico 控制器中的AggiungiAlloScarico 操作方法应该会被触发。此方法只是将所选项目添加到会话中的对象,然后将用户重定向到同一控制器内的Index 视图,这是一种“购物车”页面,他们稍后可以选择确认或返回原始页面。

[HttpPost]
public RedirectToRouteResult AggiungiAlloScarico(string Modello, string returnUrl)
{
    InventoryItem item = itemRepository.Inventario.FirstOrDefault(i => i.Item.Modello == Modello).Item;

    if (item != null)
    {
        GetScarico().AddItem(item, 1);
    }

    return RedirectToAction("Index", new { returnUrl });
}

问题是这个动作方法根本没有被触发。我认为路由可能有问题,因为每次按下“Consegna”按钮时,我都会被重定向到localhost:port/Scarico/AggiungiAlloScarico 页面:该url 构造对应于默认路由映射(RoutConfig 类中的最后一个方法) ,但未调用相关操作。此外,我在方法上设置了一个断点,但它永远不会停在那里,所以我想问题就在这里,但我真的看不到它。

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

    routes.MapRoute(
        null,
        "",
        new { controller = "magazzino", action = "inventario", manufacturer = (string)null, page = 1 }
    );

    routes.MapRoute(
        null,
        "Page{page}",
        new { controller = "magazzino", action = "inventario", manufacturer = (string)null },
        new { page = @"\d+" }
    );

    routes.MapRoute(
        null,
        "{manufacturer}",
        new { controller = "magazzino", action = "inventario", page = 1 }
    );

    routes.MapRoute(
        null,
        "{modello}",
        new { controller = "magazzino", action = "inventario", manufacturer = (string)null, page = 1 }
    );

    routes.MapRoute(
        null,
        "{manufacturer}/Page{page}",
        new { controller = "magazzino", action = "inventario" },
        new { page = @"\d+" }
    );

    routes.MapRoute(
        null,
        "{manufacturer}/{modello}",
        new { controller = "magazzino", action = "inventario", page = 1 }
    );

    routes.MapRoute(null, "{controller}/{action}");
}

所有其他路由都是为了处理过滤和导航系统而创建的,效果很好。

编辑: 我注释掉了除默认路由之外的所有路由,并且它有效。我的自定义路线有什么问题?

感谢任何帮助。

谢谢, 大卫。

【问题讨论】:

  • 你的方法有必要的[HttpPost]属性吗?
  • @StephenMuecke 是的。将其添加到原始问题

标签: asp.net-mvc-5 routing


【解决方案1】:

添加路由的顺序很重要。路由引擎将采用与提供的 URL 匹配的第一个路由,并尝试使用该路由中的路由值。尝试使用 Attribute Routing 来注释 action 方法,如果可行,那么大多数情况下应该使用路由的顺序。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-10
    • 1970-01-01
    • 2016-05-07
    • 1970-01-01
    • 1970-01-01
    • 2014-09-18
    相关资源
    最近更新 更多