Monday, 6 October 2014

Bind Dropdownlist using JQuery AJAX in ASP.NET OR Calling ASP.NET WebMethod using jQuery AJAX C#/VB.NET

Hi friends,in this article I will explain about how to Bind Dropdownlist using JQuery AJAX in ASP.NET OR Calling ASP.NET WebMethod using jQuery AJAX C#/VB.NET
I already explained in the previous articles about Ajax AsyncFileUpload control example in asp.net to upload files to server using C#/VB.NETHow to Build Modal Popup using ASP.Net AJAX ModalPopupExtender Control in ASP.NET and How to use Ajax FilteredTextBoxExtender for validating in ASP.NET
jQuery allows you to call Server Side ASP.net methods from client side without any PostBack. Actually it is an AJAX call to the server but it allows us to call the method or function defined server side.
ASP.NET:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Bind Dropdownlist using JQuery AJAX in ASP.NET OR Calling ASP.NET WebMethod using jQuery AJAX C#/VB.NET</title>
    <script src="Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        function BindDropDown() {
            $.ajax({
                type: "POST",
                url: "CallWebMethodJquery.aspx/BindDropdownlist",
                data: '',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: OnSuccess,
                failure: function (response) {
                    alert("Failure");
                }
            });
        }
        function OnSuccess(response) {
            var jsdata = JSON.parse(response.d);
            $.each(jsdata, function (key, value) {
                $('#<%=ddlUsers.ClientID%>').append($("<option></option>").val(value.User_ID).html(value.UserName));
            });
        }
        function ShowSelectedUser() {
            var ddlUser = $("#ddlUsers option:selected").text();
            alert(ddlUser);
        }
    </script>
</head>
<body onload="BindDropDown()">
    <form id="form1" runat="server">
    <div>
        Select Name :
        <asp:DropDownList ID="ddlUsers" runat="server">
        </asp:DropDownList>
        <br />
        <asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClientClick="ShowSelectedUser()" />
    </div>
    </form>
</body>
</html>
Above the BindDropdownlist method makes an AJAX call to the server and executes the BindDropdownlist  webmethod.
C#:
using System.Web.Services;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.Script.Serialization;

public partial class CallWebMethodJquery : System.Web.UI.Page
{
   
    [WebMethod]
    public static string BindDropdownlist()
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ConnectionString);
        SqlCommand cmd = new SqlCommand("select User_ID,userName from User_Details ORDER BY USER_ID ASC", con);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds);
        List<User> listUser = new List<User>();

        if (ds.Tables[0].Rows.Count > 0)
        {
            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                User objst = new User();
                objst.User_ID = Convert.ToInt32(ds.Tables[0].Rows[i]["User_ID"]);
                objst.UserName = Convert.ToString(ds.Tables[0].Rows[i]["userName"]);
                listUser.Insert(i, objst);
            }

        }
        JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
        return jsSerializer.Serialize(listUser);
    }
    public class User
    {
        public int User_ID { get; set; }
        public string UserName { get; set; }
    }
}

VB.NET:
Imports System.Web.Services
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Imports System.Web.Script.Serialization

Partial Public Class CallWebMethodJquery
    Inherits System.Web.UI.Page

    <WebMethod()> _
    Public Shared Function BindDropdownlist() As String
        Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("con").ConnectionString)
        Dim cmd As New SqlCommand("select User_ID,userName from User_Details ORDER BY USER_ID ASC", con)
        Dim da As New SqlDataAdapter(cmd)
        Dim ds As New DataSet()
        da.Fill(ds)
        Dim listUser As New List(Of User)()

        If ds.Tables(0).Rows.Count > 0 Then
            For i As Integer = 0 To ds.Tables(0).Rows.Count - 1
                Dim objst As New User()
                objst.User_ID = Convert.ToInt32(ds.Tables(0).Rows(i)("User_ID"))
                objst.UserName = Convert.ToString(ds.Tables(0).Rows(i)("userName"))
                listUser.Insert(i, objst)

            Next
        End If
        Dim jsSerializer As New JavaScriptSerializer()
        Return jsSerializer.Serialize(listUser)
    End Function
    Public Class User
        Public Property User_ID() As Integer
            Get
                Return m_User_ID
            End Get
            Set(value As Integer)
                m_User_ID = Value
            End Set
        End Property
        Private m_User_ID As Integer
        Public Property UserName() As String
            Get
                Return m_UserName
            End Get
            Set(value As String)
                m_UserName = Value
            End Set
        End Property
        Private m_UserName As String
    End Class
End Class

The output of the above code as shown in the below figure.
When you select the item in the dropdownlist and click on the Submit button then alert will be shown as in the below figure.



You can download the code by clicking on the below Download image. 

No comments:

Post a Comment

© 2012-2014 Aspdotnet-Kishore.blogspot.com. All Rights Reserved.
The content is copyrighted to Kishore and may not be reproduced on other websites without permission from the owner.