简体   繁体   中英

How to send integer value of textbox to [WebMethod] using ajax jQuery

[code page="c#"]
[WebMethod]
public static int bubblesort(int[] arr)
{       
   //some code here

    return arr;
}

 var text; $(document).ready(function() { $("#submit").on("click", function() { text = $("#text1").val(); option = $('#dropdownfilter').val(); bsortedarr(text); }); }); function bsortedarr(text) { $.ajax({ type: "POST", url: "default.aspx/bubblesort", data: JSON.stringify({ arr: text }), contentType: "application/json; charset=utf-8", dataType: "json", success: function(response) { //code }, error: function(response) { //code } }); } 

I created WebMethod which return sorted list of array using bubblesort. When I select option bsort and give integer as input such as 100,10,1 into textbox. So I am passing that textbox value into ajax call by using stringify({ arr: text}) . I want to pass this text value which is "100,10,1" into WebMethod but it is not happening. So I am trying to split this with ',' and want to return array format list but it is in integer type so not able to return.

You should first define the atxt variable. It will hold the value of the textbox, the code will be something like this:

var atxt = $('TEXTBOX_SELECTOR').val();

After that use this variable to pass value through ajax.

Version 1
Changes in your WebMethod:

  • If you want to return an array, change the return type to object
  • Split your text then convert your array to a List of int
  • If you want to sort the List, simply use Sort() instead of a loop

WebMethod updated:

[WebMethod]
public static object bubblesort(string arr)
{
    // Split then convert to List<int>
    var sra = arr.Split(',').Select(int.Parse).ToList();
    // Sort the List
    sra.Sort();

    return sra;
}


Version 2
If you changed your WebMethod parameter type to int[] , simply sort the array:

text = $("#text1").val();
var pattern = new RegExp(/^[0-9]+(,[0-9]+)*$/);
var isNumbers = pattern.test(text.replace(/\s+/g, ''));

Test if input is a list of numbers separated by a comma:

data: JSON.stringify({ arr: text.split(',') })

And split your text :

 data: JSON.stringify({ arr: text.split(',') }) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM