Click here to Skip to main content
15,894,460 members

Populate a Drop Down List using AJAX PageMethods and Javascript

Anurag Sinha V asked:

Open original thread
Hello People,
Greetings from Anurag..
Ran into a problem today. I am trying to populate a dropdownlist via AJAX PageMethods,values for the DropDown list have to come from a SQL table.
Wrote a function in the Data Access Layer which actually returns a List after interacting with the SQL table.
Then, wrote a method in the Default.aspx.cs as a System.Web.Services.WebMethod, which actually will be called from a Javascript function.
When I start debugging, I encounter a NullReference exception when the Data Access Layer object is called in the static WebMethod in the Default.aspx.cs page.
I don't understand what am I missing over here. Experts please guide.

Below are my codes:

DAL.cs:
C#
public class DAL
{
    SqlConnection xconn = new SqlConnection(ConfigurationManager.ConnectionStrings["Connect"].ToString());

    public List<Country> populateCountryDropDown()
    {
        List<Country> listObj = new List<Country>();
        SqlDataAdapter da = new SqlDataAdapter("Select * from Sample.dbo.Country", xconn);
        DataTable dt = new DataTable();
        try
        {
            xconn.Open();
            da.Fill(dt);
            if (dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    Country obj = new Country();
                    obj.id = dt.Columns[0].ToString();
                    obj.name = dt.Columns[1].ToString();
                    listObj.Add(obj);
                }
            }
        }
        catch
        {
            throw new ApplicationException("Some error has happened");
        }
        finally
        {
            xconn.Close();
        }
        return listObj;
    }

}


Default.aspx.cs:
C#
public partial class _Default : System.Web.UI.Page
{

    [System.Web.Services.WebMethod]
    public static List<Country> populate()
    {
        DAL obj=new DAL();//Getting NullReference exception over here
        List<Country> listobject = obj.populateCountryDropDown();
        return listobject;
    }

    protected void Page_Load(object sender, EventArgs e)
    {

    }
}


Default.aspx:
XML
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="X-UA-Compatible" content="IE=8"/>
    <title></title>
    <link href="StyleSheet.css" rel="stylesheet" type="text/css" />
    <script type = "text/javascript">
    var countries;
    function CallMe() {
        countries= document.getElementById("<%=ddlCountry.ClientID %>");
        countries.options.length == 0;
    AddOption("Loading", "0");
    PageMethods.populate(OnSuccess);
}
window.onload = CallMe;
function OnSuccess(response) {
    countries.options.length = 0;
    AddOption("Please select", "0");
    for (var i in response) {
        AddOption(response[i].Name, response[i].value);
    }
}
function AddOption(text, value22) {
    var option = document.createElement('<option value="' + value22 + '">');
    countries.options.add(option);
    option.innerText = text;
}
</script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <h2>Let's populate DropDowns using Javascript and AJAX along with DataBases</h2>
        <p>&nbsp;</p>
        <p>
            <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
            </asp:ScriptManager>
            <asp:DropDownList ID="ddlCountry" runat="server">
            </asp:DropDownList>
        </p>
        <p>&nbsp;</p>
        <p>
            <asp:DropDownList ID="ddlStates" runat="server">
            </asp:DropDownList>
        </p>
    </div>
    </form>
</body>
</html>


Country.cs:
C#
public class Country
{
    private string _id;
    public string id
    {
        get { return _id; }
        set { _id = value; }
    }
    private string _name;
    public string name
    {
        get { return _name; }
        set { _name = value; }
    }
}


Is it that I can't populate values from a database using an AJAX PageMethod?
Any help or pointer would be highly appreciable.
-Anurag
Tags: C#, Javascript, Ajax, ASP.NET

Plain Text
ASM
ASP
ASP.NET
BASIC
BAT
C#
C++
COBOL
CoffeeScript
CSS
Dart
dbase
F#
FORTRAN
HTML
Java
Javascript
Kotlin
Lua
MIDL
MSIL
ObjectiveC
Pascal
PERL
PHP
PowerShell
Python
Razor
Ruby
Scala
Shell
SLN
SQL
Swift
T4
Terminal
TypeScript
VB
VBScript
XML
YAML

Preview



When answering a question please:
  1. Read the question carefully.
  2. Understand that English isn't everyone's first language so be lenient of bad spelling and grammar.
  3. If a question is poorly phrased then either ask for clarification, ignore it, or edit the question and fix the problem. Insults are not welcome.
  4. Don't tell someone to read the manual. Chances are they have and don't get it. Provide an answer or move on to the next question.
Let's work to help developers, not make them feel stupid.
Please note that all posts will be submitted under the http://www.codeproject.com/info/cpol10.aspx.



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900