You must Sign In to post a response.
  • Category: .NET

    Passing bulk array values to codebehind(cs) using ajax

    I have to pass bulk array values to code behind (cs) using ajax i had researched a lot and used this code but it didnot worked for me below is the code that i used what i need is i need to pass bulk array values in code behind(cs) using ajax

    <script>
    // Grab the information
    debugger
    var values = {"1,","2","3"};
    var theIds = JSON.stringify(values);

    // Make the ajax call
    $.ajax({
    type: "POST",
    url: "Default.aspx/Done", // the method we are calling
    contentType: "application/json; charset=utf-8",
    data: {ids: theIds },
    dataType: "json",
    success: function (result) {
    alert('Yay! It worked!');
    },
    error: function (result) {
    alert('Oh no :(');
    }
    });
    </script>
    </head>
    <body>
    <form id="form1" runat="server">
    <div>
    <asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="Default.aspx/Done" />
    </div>
    </form>
    </body>

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.Services;

    namespace PassingValueFromJavascriptToCs
    {
    public partial class WebForm3 : System.Web.UI.Page
    {
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    [WebMethod]
    public static void done(string[] ids)
    {
    String[] a = ids;
    // Do whatever processing you want
    // However, you cannot access server controls
    // in a static web method.
    }
    }
    }
  • #767057
    Either you can send Plain text or JSON. But there is an issue in your code. You are sending the content type "application/json", but you are sending the invalid JSON input. {"1,","2","3"} is not a valid JSON string . { "ids": "1,2,3" } is the valid JSON. You can validate the json in "http://jsonlint.com/". In the web method you an receive the Sting and convert it into the array.
    By Nathan
    Direction is important than speed

  • #767065
    I think JSON is the good way
    see below snippet

    var array = [ 'item1', 'item2', 'item3' ];
    $.ajax({
    url: '/foo.aspx/SaveView',
    type: 'POST',
    contentType: 'application/json',
    data: JSON.stringify({ myArray: array }),
    success: function(result) {
    }
    });

    If your Page Method returns something, you should use the result.d property in the success callback to fetch the result of the page method call.
    hope it helps

    Thanks
    Koolprasd2003
    Editor, DotNetSpider MVM
    Microsoft MVP 2014 [ASP.NET/IIS]


  • Sign In to post your comments