Search code examples
javascriptc#asp.netwebmethod

Pass C# Data Result to JavaScript Variable


I need to pass the SQL results from below to Javascript in ASP.Net? I've tried to declare the two fields in JS but can't get it right. How do I get the results in JS?

     var Description = "<%=this.Description%>"
     var ApplicationSourceCount = "<%=this.ApplicationSourceCount%>"

Declared the strings in C#

    public class ApplicantSourceData
    {
        public string Description { get; set; }
        public string ApplicantSourceCount { get; set; }
    }

C# WebMethod

[WebMethod]
    public List<ApplicantSourceData> GetApplicantSourceData(List<string> aData)
    {
        //SqlDataReader reader;
        List<ApplicantSourceData> GetApplicantSourceData = new List<ApplicantSourceData>();

        string connectionString = ConfigurationManager.ConnectionStrings["ATL2"].ConnectionString;
        string commandTextApplicantsByMonthCount = Properties.Queries.commandTextApplicantsByMonthCount;

        using (SqlConnection con = new SqlConnection(connectionString))
        {
            using (SqlCommand command = new SqlCommand(commandTextApplicantsByMonthCount))
            {

                command.CommandText = commandTextApplicantsByMonthCount;
                command.CommandType = CommandType.Text;
                command.Connection = con;
                con.Open();
                SqlDataReader reader = command.ExecuteReader();
                if (reader.HasRows)
                {
                    int counter = 0;
                    while (reader.Read())
                    {
                        ApplicantSourceData tsData = new ApplicantSourceData();
                        tsData.Description = reader["Description"].ToString();
                        tsData.ApplicantSourceCount = reader["ApplicantSourceCount"].ToString();
                        GetApplicantSourceData.Add(tsData);
                        counter++;
                    }
                }
            }
            return GetApplicantSourceData;
        }
    }

I've tried the following, but it doesn't


Solution

  • You should be calling your WebMethod from the client-side (e.g., as an AJAX request). You should then have the WebMethod return a response to the client with the requested data (e.g., as a JSON-formatted string).

    There's a couple ways to do this. The first is using AJAX.

    Example:

    C#:

    [WebMethod]
    public static string someWebMethod(String data) {
    
        // your code here
        var returnData = /* some kind of data */
        JavaScriptSerializer json = new JavaScriptSerializer();
        return json.Serialize(returnData);
    
    }
    

    JS (using jQuery for the example, but you could do this in regular JS too):

    $.ajax({
      type: "POST",
      url: "PageName.aspx/someWebMethod",
      data: "{"data": data}",
      contentType: "application/json; charset=utf-8",
      dataType: "json",
      success: function(response) {
        // Do something with the response.
      }
    });
    

    Another option is to use PageMethods. To do this, you could call the method from your JS following a pattern like this:

    PageMethods.someWebMethod(data);
    
    function onSucess(result) {
        console.log(result);
    }
    
    function onError(result) {
        console.log(result);
    }
    

    I'd suggest looking into the ASP.NET WebMethod documentation a little more too. Also, here's a couple tutorials that might help: Calling ASP.NET WebMethod using jQuery-AJAX and Calling an ASP.NET C# Method (Web Method) Using JavaScript.