JQuery Retrieving Multiple Values from Generic Handler

817 views Asked by At

After doing a search on Google and reading documentation, I am confused how this works. When calling a generic handler with a value and returning multiple values on success. How do you loop through the records in the database? Do you loop through the records on the generic handler or on success with an JQuery Each Function? Below is my current code that does not work when multiple values exist. Delete the $.each(vardata, function () and it works; however, only one record is shown.

This is how the data should look after you type in Erie in the textbox and click on the button

Business Profile ID: 8 
Business Name: The Boston Store
Phone Number: 814-455-1478
E-Mail: [email protected]

Business Profile ID: 9
Business Name: Sam The Man Pizza
Phone Number: 814-868-3809
E-Mail: [email protected]

JQuery Script

    $(document).ready(function () {
        $('#button').click(function () {
            $.ajax({
                contentType: "text/html; charset=utf-8",
                data: "ID=" + $('#businessSelect').val(),
                url: "getTest.ashx",
                dataType: "text",
                success: function (data) {
                    var vardata = JSON.parse(data);
                    $.each(vardata, function (index, value) {
                        $("#BusProfileID").html(value.BusProfileID);
                        $("#BusinessName").html(value.BusinessName);
                        $("#BusinessPhone").html(value.BusinessPhone);
                        $("#BusinessEmail").html(value.BusinessEmail);
                    });
                }
            })
        });
    });

ashx handler page

     public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/html";
        string ID = context.Request.QueryString["ID"];
        SqlConnection conn;
        SqlCommand comm;
        SqlDataReader reader;
        string connectionString = ConfigurationManager.ConnectionStrings["Conn"].ConnectionString;
        conn = new SqlConnection(connectionString);
        comm = new SqlCommand("SELECT BusProfileID, BusinessName, BusinessPhone, BusinessEmail FROM [BusProfile] WHERE BusinessCity = @BusinessCity", conn);
        comm.Parameters.Add("@BusinessCity", System.Data.SqlDbType.VarChar);
        comm.Parameters["@BusinessCity"].Value = ID;
        try
        {
            conn.Open();
            reader = comm.ExecuteReader();
            List<BusinessData> objList = new List<BusinessData>();
            BusinessData objData;
            while (reader.Read())
            {
                objData = new BusinessData();
                objData.BusProfileID = reader["BusProfileID"].ToString();
                objData.BusinessName = reader["BusinessName"].ToString();
                objData.BusinessPhone = reader["BusinessPhone"].ToString();
                objData.BusinessEmail = reader["BusinessEmail"].ToString();
                objList.Add(objData);
                context.Response.Write(JsonConvert.SerializeObject(objList));
            }
            reader.Close();
        }

        finally
        {
            conn.Close();
        }
    }

    public class BusinessData
    {
        public string BusProfileID { get; set; }
        public string BusinessName { get; set; }
        public string BusinessPhone { get; set; }
        public string BusinessEmail { get; set; }
    }
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

ASPX Page

            <div class="row">
                <div class="columns medium-12">
                    <div class="row">
                       <div class="medium-6 columns medium-centered">
                            <label style="font-size:1em">Select City:</label>
                            <input type="text" id="businessSelect" style="height:2em;" /> <input type="button" id="button" value="Click me" />
                      </div>
                    </div>
                    <div class="row">
                       <div class="medium-6 columns medium-centered">
                            <label style="font-size:1em">Business Profile ID:</label>
                            <label id="BusProfileID" style="font-size:1em;"></label>
                      </div>
                    </div>
                    <div class="row">
                       <div class="medium-6 columns medium-centered">
                            <label style="font-size:1em">Business Name:</label>
                            <label id="BusinessName" style="font-size:1em;"></label>
                      </div>
                    </div>
                    <div class="row">
                        <div class="medium-6 columns medium-centered">
                            <label style="font-size:1em">Phone Number:</label>
                            <label id="BusinessPhone" style="font-size:1em;"></label>
                        </div>
                    </div>
                    <div class="row">
                        <div class="medium-6 columns medium-centered">
                            <label id="BusinessEmail" style="font-size:1em">E-Mail:</label>
                        </div>
                    </div>
                </div>
1

There are 1 answers

2
Muhammed Shevil KP On

If you want to loop through result, it must be an object. Now you are stringifying your result. so you cant iterate it.

Use JSON.parse to convert the result to JSON object then use $.each on that object

var vardata = JSON.parse(data);
$.each(vardata, function (index, value) {
    // TODO
});

So you will not need to split and take into array. you can refer value parameter in each statement.

EDIT

To use the values from the JSON, you can use its properties as set from the server result.

Like,

$.each(vardata, function (index, value) {
    $("#BusProfileID").html(value.BusProfileID);
    $("#BusinessName").html(value.BusinessName);
    $("#BusinessPhone").html(value.BusinessPhone);
    $("#BusinessEmail").html(value.BusinessEmail);
});

Use a class to keep the data you retrieved from SQL Query

public class BusinessData
{
    public long BusProfileID { get; set; }
    public string BusProfileID { get; set; }
    public string BusProfileID { get; set; }
    public string  BusProfileID { get; set; }
}

Create a List<BusinessData> object and add each items from your reader to this list

reader = comm.ExecuteReader();
List<BusinessData> objList = new List<BusinessData>();
BusinessData objData;
while (reader.Read())
{
    objData = new BusinessData();
    objData.BusProfileID = reader["BusProfileID"].ToString();
    objData.BusinessName = reader["BusinessName"].ToString();
    objData.BusinessPhone = reader["BusinessPhone"].ToString();
    objData.BusinessEmail = reader["BusinessEmail"].ToString();
    objList.Add(objData);
    context.Response.Write(JsonConvert.SerializeObject(objList));
}
reader.Close();

JsonConvert is included in Newtonsoft.Json nuget package.