How to populate asp.net dropdown list from database by passing radio button list’s selected value as parameter with JQuery?

How to populate asp.net drop down list from database by passing radio button list’s selected value as parameter with J Query, J Son?

In my project I am taking off asp.net update panel where ever possible and replacing it with J Query Ajax. J Query Ajax is far better then asp.net Ajax and asp.net update panel.  I am populating 259 countries list on the basis of parameter passed from asp.net radio button list’s selected text. Using asp.net radio button list and drop down list inside asp.net update panel keeping Radio button list’s auto post back property to true. First time running application from visual studio and clicking on the radio button list item populated drop down list in “176ms” and when chose same option second time it took “76ms” while same Ajax request using J query  took “79ms” for first time and  when chose same option second time it took “32ms”.

J Query code to decode j son result and populate asp.net drop down list

<script type=”text/javascript”>

function getCountries()

{

var elementId = ‘<%=rblUKInternational.ClientID%>’;

var elementRef = document.getElementById(elementId);

var checkBoxArray = elementRef.getElementsByTagName(‘input’);

var checkedValue =“”;

var isChecked = false;

for (var i = 0; i < checkBoxArray.length; i++) {

if (document.getElementById(elementId + “_” + i.toString()).checked == true) {

var checkBoxRef = checkBoxArray[i];

checkedValue=checkBoxRef.value;

Chekced = false;

break;

}

}

$.ajax({

type:“POST”,

url:“WebService/WsCountry.asmx/getCountryList”,

data:“{optionvalue:’”+checkedValue+“‘}”,

contentType:“application/json; charset=utf-8″,

dataType:“json”,

success:function(response)

{

if (response.length<=4)

{

alert (response);

}

else

{

var myObject= eval(“(“+ eval(response)+ “)”);

$(‘#<%=DropDownListCountry.ClientID %>>option’).remove();

$(“#<%=DropDownListCountry.ClientID %>”).append($(‘<option></option>’).val().html(“Please select…”));

for (var i=0;i<=myObject.length-1;i++) {

$(“#<%=DropDownListCountry.ClientID %>”).append($(‘<option></option>’).val(myObject[i].countrycode).html(myObject[i].name));

}

}

},

error: function (response)

{

if (response.length!=0)

alert(response.status + ‘ ‘ + response.statusText);

}

});

}</script>

Web service code to get data from SQL server 2005 and encode into J Son format

using System;

using System.Data;

using System.Web;

using System.Collections;

using System.Web.Services;

using System.Web.Services.Protocols;

using System.ComponentModel;

using System.Web.Script.Services;

using System.Web.Script.Serialization;

using System.Text;

using System.Collections.Generic;

{

/// <summary>

/// Summary description for WsCountry

/// </summary>

[ScriptService]

public class WsCountry : System.Web.Services.WebService

{

[WebMethod]

public string getCountryList(string optionvalue)

{

try

{

StringBuilder sbcountriesList = new StringBuilder();

if ((optionvalue != “GB”) &&

(optionvalue != “INT”))

throw new ApplicationException(string.Format(“Country code GB or INT expected, {0} received”, optionvalue));

CountryService cs = new CountryService();

TList<Country> countries = cs.GetAll(optionvalue);

List<Dictionary<string, string>> rows = new List<Dictionary<string, string>>();

foreach (Country country in countries)

{

Dictionary<string, string> Dictionary = new Dictionary<string, string>();

Dictionary.Add(“name”, country.DisplayName);

Dictionary.Add(“countrycode”, country.CountryCode);

rows.Add(Dictionary);

}

JavaScriptSerializer js = new JavaScriptSerializer();

js.Serialize(rows, sbcountriesList);

return sbcountriesList.ToString();

}

catch (Exception ex)

{

return ex.Message;

}

}

}

}

C# code to call JavaScript function on the radio button list selected item

this.rblUKInternational.Attributes.Add(“onclick”,“getCountries()”);

Json, Jquery, $.ajax(), asp.net and c# to get ajaxed data table rows passing multiple parameters



Json, Jquery, $.ajax(), asp.net  and c# to get ajaxed data table rows passing multiple parameters

I got a request from my client that before creating user they want to see the list of existing users with the like  first name and last name.

I didn’t want to use asp.net ajax update panel and full post back as its extremly slow, I used Jquery $ajax which is excellent

I planned to use Jquery ajax,  as we know to use Jquery we need to get our results in Json format. Then we need to format json result using javascript to show the user friendly data to users.


I started working through my solution

First shock I got

JavaScriptSerializer js = new JavaScriptSerializer();

js.Serialize(rows, sb);

above method serializes the object passed to it to json , you know what I passed as my object to this method,  I passed my data table rows in it and it failed then I passed table in it and it failed so I started looking for the solotion over the internet found quite few solutions but them were not fitting to my need one found in asp.net foums was fitting to my need btu there were errors in teh code then I managed to resolve those erros   . [sb is StringBuilder] used in my method].

Div to show the result

Following is the result div in which I’ll be showing my final resutl on  asp.net page

<div id=”divAjax”></div>

<asp:Button ID=”btnAdd” runat=”server” Text=”Create new user” OnClick=”btnAdd_Click” OnClientClick=”findUserBeforeCreate()” />

This is the page method which takes first name an last name  as input parameters passed and returns json result as string.

[WebMethod]

public static string findUsersAjax(string firstName, string lastName)

{

StringBuilder sb = new StringBuilder();

UsersService userService = new UsersService();

string strFind = String.Format(“FirstName like ‘{0}%’ AND LastName like ‘{1}%’ “, firstName.Trim(), lastName.Trim());

DataTable dt = userService.FindUsers(strFind).Tables[0];

List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();

Array.ForEach(

dt.Select(), delegate(DataRow row)

{

Dictionary<string, object> Dictionary = new Dictionary<string, object>();

foreach (DataColumn col in dt.Columns)

Dictionary.Add(col.ColumnName, row[col].ToString());

rows.Add(Dictionary);

}

);

JavaScriptSerializer js = new JavaScriptSerializer();

js.Serialize(rows, sb);

return sb.ToString();

}

Follwoign Java Script funtion which, I am calling on the click event of the button calls the c# method  it  first name and last name as input parametters which then are passed to c# method.

function findUserBeforeCreate()

{

var lastName= $(“#<%=txtLastName.ClientID%>”).val();

var firstName= $(“#<%=txtFirstName.ClientID%>”).val();

if (lastName.length<=0 || firstName.length<=0)

{

return false;

}

else

{

$.ajax({

type:”POST”,

url:”/Admin/SDUsers.aspx/findUsersAjax“,

data:”{firstName:’”+firstName+”‘,lastName:’”+lastName+”‘}”,

contentType:”application/json; charset=utf-8″,

dataType:”jsondata”,

success:function(response)

{ if (response.length<=4) {

$(“#divAjax”).hide(“fast”);

}

else {

var myObject= eval(“(“+ eval( response) + “)”);

BuildTable(myObject);

$(“#divAjax”).show(“fast”);

}

},

error: function (response){

alert(response.status + ‘ ‘ + response.statusText);

}

});

}

}

Struggle point: I was returning Restuls in Json but javascript eval function was not working for me and it took few hours to resolve the issue thanks to http://www.javascriptkata.com/2007/05/08/how-to-use-json/#comment-710

var myObject= eval(“(“+ eval( response) + “)”);

I was using it like var myObject= eval(“(“+  response + “)”); and struggled as it was treating result as single string not as an array, then using it in thsi way It worked for me var myObject= eval(“(“+ eval( response) + “)”);

Followign java script function is to create table to show the users

function BuildTable(msg) {

if ($(‘#tblResult’).length != 0) // remove table if it exists
{
$(“#tblResult”).remove();}

var table = ‘<table id=tblResult><thead> <tr><th>User Id</th>    <th>Password</th>   <th>First Name</th>   <th>Last Name</th></thead>  <tbody>’;

for (var i=0;i<=msg.length-1;i++) {

var row = ‘<tr>’;

row += ‘<td>’ + msg[i].UserId + ‘</td>’;

row += ‘<td>’ + msg[i].Password+ ‘</td>’;

row += ‘<td>’ + msg[i].FirstName+ ‘</td>’;

row += ‘<td>’ +msg[i].LastName+ ‘</td>’;

row += ‘</tr>’;

table += row;

}

table += ‘</tbody></table>’;

$(‘#divAjax’).html(table);

}


|