Hi, Please find the code snippet to bind the dropdownlist dynamically using storedprocedure (Ajax and jquery).I have not used Linq but I have used Sql server database.Hope this will help.
Aspx Page:
************
<![CDATA[<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="MachineCode.aspx.cs" Inherits="SampleApp.MachineCode" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "POST",
contentType: "application/json;charset=utf-8",
//URL is the path of our Ajax webmethod (pagename/functionname
url: "MachineCode.aspx/PopulateDropDownList",
data: "{}",
dataType: "json",
//Called the jquery ajax call success
success: function (result) {
$("#ddlStates").empty();
$("#ddlStates").append("<option value="0">--Select--</option>");
$.each(result.d, function (key, value) {
$("#ddlStates").append($("<option></option>").html(value.State));
});
},
//called on jquery ajax call failure
error: function ajaxError(result) {
alert(result.status + ':' + result.statusText)
}
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
Populate a dropdown Dynamically via stored procedure
States Name:
<asp:dropdownlist id="ddlStates" runat="server" width="160px" xmlns:asp="#unknown">
<asp:label id="dbErrorLabel" runat="server" visible="False" xmlns:asp="#unknown">Label
</form>"server" Visible="False">Label
</form>
</body>
</html>
**************************
CodeBehind:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Web.Services;
using System.Configuration;
namespace SampleApp
{
public partial class MachineCode : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
public class States
{
public string State { get; set; }
public string Country { get; set; }
}
[WebMethod]
public static List<states> PopulateDropDownList()
{
DataTable dt = new DataTable();
List<states> objStates = new List<states>();
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Name_Of_Your_SP"].ConnectionString))
{
using (SqlCommand cmd = new SqlCommand("GeographyLocations", con))
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
objStates.Add(new States
{
State = dt.Rows[i]["States"].ToString(),
//Country = dt.Rows[i]["Countries"].ToString()
});
}
}
return objStates;
}
}
}
}
}