开发者

Including an array with a serialize form - jquery

I currently have a form that I am trying to perform a post on (serializing the form), however I also want to include several checkboxes (but I don't want to include them in the form itself)

I have开发者_如何学C tried using jQuery's .post, but was unable to accomplish what I needed, any help would be greatly appreciated.

(I am using asp.net MVC 2.0 - and I figured this event would be attached to a button click)


There are several ways to accomplish this, I'll demonstrate two for you, along with an example of a Controller Action to accept the data:

Your Controller Action:

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

.post Method:

//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 Method:

//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
               }
});

I hope this helps you accomplish what you need.


Would something like this work for you? (assuming the button is the submit button on the form)

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜