locked
jQuery to WebMethod, pass comma separated list RRS feed

  • Question

  • User-1826049516 posted

    Hey,

    I want to pass the values of all checked checkboxes to a WebMethod.  I'm having trouble with this.

    JS:

    var values = $( "input:checkbox:checked." + opt ).map( function() {
    
    	return this.value;
    
    }).get();
    
    ...
    
    request = $.ajax({
    
    	type: "POST",
    	url: "/webservices/Links.asmx/FavouriteLink",
    	data: "{ 'Links':'" + values + "' }",
    	contentType: "application/json; charset=utf-8",
    	dataType: "json"
    
    });
    
    

    If I alert the value of values, it returns comma separated.

    ASMX:

    [WebMethod]
    public string FavouriteLink(string links)
    {
    
    	foreach (string link in links)
    	{
    
    		LinkID = Guid.Parse(link);
    		using (Connection = new SqlConnection(BasePage.SqlConnection))
    		using (Command = new SqlCommand("genUpdUserFavLinks", Connection))
    		{
    
    			Command.CommandType = CommandType.StoredProcedure;
    
    			Command.Parameters.AddWithValue("@LinkID", link);
    			Command.Parameters.AddWithValue("@LogonUser", BasePage.LogonUser);
    
    			Connection.Open();
    			Command.ExecuteNonQuery();
    
    		}
    
    	}
    
    }
    

    Error:

    CS0030: Cannot convert type 'char' to 'string'

    What is the correct way of passing an array from JS to a WebMethod and then looping through the list in the WebMethod?

    Thanks

    Wednesday, November 4, 2015 5:52 AM

Answers

  • User475983607 posted

    This line of code is looping over each char in the string "links".  It works this way because a string is really an array of characters where the last char is a zero.

    foreach (string link in links)

    If links contains a comma separated list you need to first split the "links " into a collection if strings.

    string[] listArr = links.Split(',');
    
    foreach (string link in listArr)
    {
      //do stuff
    }

    Try using your debugger and step through the loop.  You will see what I'm talking about.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, November 4, 2015 7:45 AM
  • User632428103 posted

    Hello all,

    as said mgebhard , debug your code for to see what's happen ..

    But when i look your code i've seen the parameter pass to the web service are not the same :

    - client =>

    Links

    - server =>

    links

    You see on client the first letter in on upper case and on server the first letter is not on upper case ..

    i think normally (i'm not an expert :)) the parameter must be exactly the same ... !

    Hope this help

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, November 4, 2015 10:11 AM
  • User61956409 posted

    Hi ldoodle,

    If I alert the value of values, it returns comma separated.

    Error:

    CS0030: Cannot convert type 'char' to 'string'

    Please debug your code to find which code causes the error. Besides, as mgebhard said, you could try to use split “” to return a string array. The following simple sample is for your reference.

    <input id="chk1" type="checkbox" value="link1" />
    <input id="chk2" type="checkbox" value="link2" />
    <input id="chk3" type="checkbox" value="link3" />
    <input id="btnok" type="button" value="OK" onclick="callwebmethod()" />
    <br />
    <div id="result"></div>
    
    function callwebmethod() {
        var values = "";
        $("input[type='checkbox']:checked").each(function () {
            var val = $(this).val();
            values += val + ",";
        });
    
        if (values.length > 0) {
            $.ajax({
                type: "Post",
                url: "Default.aspx/FavouriteLink",
                data: "{ 'links':'" + values + "' }",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
                    var mes = data.d;
             $("#result").html(mes);
                },
                error: function (err) {
                    alert(err);
                }
            })
        }
    }  
    
    public static string FavouriteLink(string links)
    {
        string str = "";
        string[] linklist = links.Trim(',').Split(',');
        for (int i = 0; i < linklist.Length; i++)
        {
            str += linklist[i];
        }
        return str;
    
    }
    

    Best Regards,

    Fei Han




    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, November 5, 2015 4:29 AM

All replies

  • User475983607 posted

    This line of code is looping over each char in the string "links".  It works this way because a string is really an array of characters where the last char is a zero.

    foreach (string link in links)

    If links contains a comma separated list you need to first split the "links " into a collection if strings.

    string[] listArr = links.Split(',');
    
    foreach (string link in listArr)
    {
      //do stuff
    }

    Try using your debugger and step through the loop.  You will see what I'm talking about.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, November 4, 2015 7:45 AM
  • User632428103 posted

    Hello all,

    as said mgebhard , debug your code for to see what's happen ..

    But when i look your code i've seen the parameter pass to the web service are not the same :

    - client =>

    Links

    - server =>

    links

    You see on client the first letter in on upper case and on server the first letter is not on upper case ..

    i think normally (i'm not an expert :)) the parameter must be exactly the same ... !

    Hope this help

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, November 4, 2015 10:11 AM
  • User61956409 posted

    Hi ldoodle,

    If I alert the value of values, it returns comma separated.

    Error:

    CS0030: Cannot convert type 'char' to 'string'

    Please debug your code to find which code causes the error. Besides, as mgebhard said, you could try to use split “” to return a string array. The following simple sample is for your reference.

    <input id="chk1" type="checkbox" value="link1" />
    <input id="chk2" type="checkbox" value="link2" />
    <input id="chk3" type="checkbox" value="link3" />
    <input id="btnok" type="button" value="OK" onclick="callwebmethod()" />
    <br />
    <div id="result"></div>
    
    function callwebmethod() {
        var values = "";
        $("input[type='checkbox']:checked").each(function () {
            var val = $(this).val();
            values += val + ",";
        });
    
        if (values.length > 0) {
            $.ajax({
                type: "Post",
                url: "Default.aspx/FavouriteLink",
                data: "{ 'links':'" + values + "' }",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
                    var mes = data.d;
             $("#result").html(mes);
                },
                error: function (err) {
                    alert(err);
                }
            })
        }
    }  
    
    public static string FavouriteLink(string links)
    {
        string str = "";
        string[] linklist = links.Trim(',').Split(',');
        for (int i = 0; i < linklist.Length; i++)
        {
            str += linklist[i];
        }
        return str;
    
    }
    

    Best Regards,

    Fei Han




    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, November 5, 2015 4:29 AM