【问题标题】:POST actions with same name and different [default] params wont fire from an Ajax call具有相同名称和不同 [默认] 参数的 POST 操作不会从 Ajax 调用中触发
【发布时间】:2016-09-22 23:58:01
【问题描述】:

基本上,我有这两个动作:

[HttpPost]
[ActionName("ListarTodosGrupo")]
public ActionResult ListAllFromGroup(string wildcard = "", int registries = 10)
{
    // ...
}

[HttpPost]
[ActionName("ListarTodosGrupo")]
public ActionResult ListAllFromGroup(string cnpj, string wildcard = "", int registries = 10)
{
    // ...
}

这些操作应该是从 Ajax 调用中调用的。我要做的是根据 Ajax 调用参数(数据)调用不同的操作。例如:

$.ajax({
    url: "/Cliente/ListarTodosGrupo",
    type: "post",
    dataType: "json",
    cache: true,
    data: { // This should fire the first action
        wildcard: $("input#nomeCliente").val(),
        registries: 10
    },
    ...
});

$.ajax({
    url: "/Cliente/ListarTodosGrupo",
    type: "post",
    dataType: "json",
    cache: true,
    data: { // This should fire the second action
        wildcard: $("input#nomeCliente").val(),
        registries: 10,
        cnpj: '02696818000116' 
    },
    ...
});

但是,它不起作用(尽管给定参数的数量,但仅触发了第一个操作)。甚至可能吗?我该怎么做?

【问题讨论】:

  • 删除第一个方法。如果您没有为cnpj 发布值,那么它将只是null
  • @StephenMuecke 好点!我不得不承认我想不出这个。但是,这两个功能旨在具有不同的逻辑。第一个(没有'cnpj'参数)应该根据一些会话值找出一个有效的cnpj值,然后调用第二个动作。第二个动作应该从给定(已知)'cnpj'值的任何 ajax 调用中调用。
  • 如果为空,执行一项操作,否则执行另一项操作

标签: c# ajax asp.net-mvc-4 action default-parameters


【解决方案1】:

.NET MVC 在调用操作时不考虑重载方法,只考虑方法的名称和任何 http-verb 属性(如 HttpPost、HttpGet 等)。因此,无论您发送什么数据,都只会调用第一个方法。

您需要重新考虑您的解决方案。最简单的更改是使用一个公共方法 ListarTodosGrupos,该方法获取所有可能需要的数据,并将其他数据默认为 null(如果适用)。您为不同的功能创建私有方法。根据发送到 ListarTodoGropus 的数据,您可以让您的代码调用所需的私有方法。

【讨论】:

    【解决方案2】:
    [HttpPost]
    [ActionName("ListarTodosGrupo")]
    public ActionResult ListAllFromGroup(string wildcard = "", int registries = 10)
    {
        // ...
    }
    
    [HttpPost]
    [ActionName("ListarTodosGrupo2")]
    public ActionResult ListAllFromGroup(string cnpj, string wildcard = "", int registries = 10)
    {
        // ...
    }
    

    尚未尝试,但如果您可以将第二个方法的操作名称更改为 ListarTodosGrupo2,那么您可以使用 ajax 调用 post 方法,如下所示。

    $.ajax({
        url: "/Cliente/ListarTodosGrupo",
        type: "post",
        dataType: "json",
        cache: true,
        data: { // This should fire the first action
            wildcard: $("input#nomeCliente").val(),
            registries: 10
        },
        ...
    });
    
    $.ajax({
        url: "/Cliente/ListarTodosGrupo2",
        type: "post",
        dataType: "json",
        cache: true,
        data: { // This should fire the second action
            wildcard: $("input#nomeCliente").val(),
            registries: 10,
            cnpj: '02696818000116' 
        },
        ...
    });
    

    【讨论】:

      猜你喜欢
      • 2021-10-09
      • 2020-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多