【问题标题】:Including an array with a serialize form - jquery包括具有序列化形式的数组 - jquery
【发布时间】:2011-10-22 13:10:15
【问题描述】:

我目前有一个表单,我正在尝试在上面执行帖子(序列化表单),但是我还想包含几个复选框(但我不想将它们包含在表单本身中)

我尝试过使用 jQuery 的 .post,但无法完成我需要的工作,非常感谢任何帮助。

(我正在使用 asp.net MVC 2.0 - 我认为此事件将附加到按钮单击)

【问题讨论】:

    标签: c# jquery asp.net-mvc forms serialization


    【解决方案1】:

    有几种方法可以做到这一点,我将为您演示两种,以及一个接受数据的控制器动作示例:

    您的控制器操作:

    [HttpPost]
    public ActionResult YourActionName(YourModel formModel, bool[] checkboxes)
    {
       ...
    }
    

    .post方法:

    //Serialize Form Data
    var data = $("#yourForm").serializeArray();
    
    //Iterates through all your checkboxes - with a specific class
    $(".yourCheckboxClass").each(function ()
    {
        data.push({name : "checkboxes", value : $(this).val()});
    });
    

    .ajax方法:

    //Build array of checkbox values
    //You can use an .each here, or whatever other method you prefer
    
    $.ajax({ type: "POST",
              url: "<%= Url.Action("Action","Controller") %>",
         datatype: "json",
      traditional: true,
             data: {
                      'formModel': $('#yourForm').serialize(),
                     'checkboxes': yourCheckboxArray
                   }
    });
    

    我希望这可以帮助您完成所需的工作。

    【讨论】:

    • 我假设您将分别处理它们,否则您可以通过在模型中包含数组来完成相同的操作。
    • 是的 Rionmonster - 感谢您的快速回复。我只是无法让阵列自己正常工作。我正在尝试与您的 ajax 方法类似的方法,但略有不同。
    • 其中一个棘手的部分通常是在使用数组时您需要有传统的 : true 部分。至少根据我的经验。
    【解决方案2】:

    这样的东西对你有用吗? (假设按钮是表单上的提交按钮)

    $("#triggerButton").bind("click.me", function(e) {
       var $form = $(this).closest("form");
       $(".other-checkbox-class").appendTo($form);
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-07
      • 1970-01-01
      • 2021-01-22
      • 2023-03-11
      • 1970-01-01
      • 2013-12-22
      • 1970-01-01
      • 2017-06-05
      相关资源
      最近更新 更多