use the below code i think it will be helpful for you. i have given the code to the simialr situation ( where user selects an item in dropdownlist and populating another dropdown values )
public partial class JQ_JSON_AJAX : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
List<string> lstCountries = new List<string>();
lstCountries.Add("--select--");
lstCountries.Add("India");
lstCountries.Add("USA");
lstCountries.Add("Canada");
ddlCountries.DataSource = lstCountries;
ddlCountries.DataBind();
}
}
[WebMethod]
public static List<string> GetStates(string countryname)
{
List<string> lstStates = new List<string>();
if (countryname.ToLower() == "usa")
{
lstStates.Add("Newyork");
lstStates.Add("texax");
lstStates.Add("ohio");
}
if (countryname.ToLower() == "india")
{
lstStates.Add("KA");
lstStates.Add("TN");
lstStates.Add("KL");
}
return lstStates;
}
}
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="JQ_JSON_AJAX.aspx.cs" Inherits="JQ_JSON_AJAX" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="JquryLib.js"></script>
<script language="javascript" type="text/javascript">
function fnPopulateStates() {
debugger;
var country=$("#ddlCountries").val();
GetStates(country);
return false;
}
function GetStates(countryname) {
var v1 = 'countryname:' + "'"+countryname+"'";
$.ajax(
{
type: "POST",
url: 'JQ_JSON_AJAX.aspx/GetStates',
data: '{' + v1 + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
fnDisplayStates(result);
},
error: function (req, status, error) {
alert("Sorry! Post failed due to error");
}
});
}
function fnDisplayStates(data) {
$("#ddlStates").empty();
for (i = 0; i < data.d.length; i++) {
var option = '<option>' + data.d[i].toString() + '</option>';
$("#ddlStates").append(option);
}
return false;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
Country:<asp:DropDownList ID="ddlCountries" onchange="return fnPopulateStates()" runat="server"></asp:DropDownList><br />
States:<asp:DropDownList ID="ddlStates" runat="server"></asp:DropDownList>
</div>
</form>
</body>
</html>
Note : download jquery file from jquery.com website
for more details related to best c# interview questions and answers visit
http://skillgun.com/csharp/interview-questions-and-answers[
^]