Create a list with jquery and place it in asp.net mvc

I am looking for a way to save the values ​​of all existing flags of a given class into some list or array and send the result via jquery to the asp.net mvc controller. Flags do not need to be checked, I need all of them.

More details:

My flags are as follows

<input type="checkbox" value="1" class="a-checkbox" <input type="checkbox" value="2" class="a-checkbox" <input type="checkbox" value="3" class="a-checkbox" 

It would be nice if my MVC controller could look like this:

 public JsonResult SaveList(List<String> values) { //... } 

I know that I can access the cells as follows

  $('input.a-checkbox').each( function () { // create the list with the help of $(this).val() } ); // jquery post would happen here 

But I do not know how to create such a data structure. could you help me?

thanks

Edit: nice, thanks. Can you tell me what's wrong with that? My controller is called really, but the list is null (server side)

 var list = []; $('a-checkbox').each( function () { list.push($(this).val()); } ); $.ajax({ type: "POST", url: myUrl, data: list, success: function (data) { alert(data.Result); }, dataType: "json", traditional: true }); 
+4
source share
4 answers

This will put all checkbox ( value ) values ​​in an Array :

 var values = []; $(".a-checkbox").each(function () { values.push($(this).val()); }); // values now equals ["1", "2", "3"] 
+3
source

try it

 var list = []; $('input.a-checkbox').each( function () { // create the list with the help of $(this).val() list.push($(this).val()); } ); 

Now you can send the list object to the action of your mvc controller.

+1
source

I use .Serialize () to format form data for my mjc ajax actions.

 var checkPostData = $(".a-checkbox").serialize(); 

http://api.jquery.com/serialize/

+1
source

I had the same Nulls problem in my MVC mode and all. I found using $ ("input: checked"), because my data, instead of trying to extract the values ​​into an array in js, worked better, and I fixed the Nulls problem by specifying my name values ​​in cells, because MVC binds to input names .

HTML

 <a class="post-checkboxes" href="#">post checkboxes</a> <input name="[MVC viewmodel list variable name]" type="checkbox" value="1" /> <input name="[MVC viewmodel list variable name]" type="checkbox" value="2" /> 

Javascript

 $('.post-checkboxes').click(function (e) { e.preventDefault(); $.post("[location to post to]", $("input:checked")); }); 
0
source

Source: https://habr.com/ru/post/1385348/


All Articles