Thursday, August 18, 2016

How to use AJAX DynamicPopulateExtender in ASP.NET

In this article I will explain how to use AJAX DynamicPopulateExtender in ASP.NET.

Consider an example on which if a user enters ID of an agent in a textbox , it
will display name of the agent from the database in a label.

HTML Code (.aspx) :


<head runat="server">
    <title></title>
    <script type="text/javascript">
        function UpdateControl(value) {
            var behavior = $find('dp1');
            if (behavior) {
                behavior.populate(value);
            }
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager runat="server">
    </asp:ScriptManager>

    <asp:TextBox ID="txtID" runat="server" onblur="UpdateControl(this.value);"></asp:TextBox>

    <asp:Label ID="lblName" runat="server" Text="Label"></asp:Label>

    <cc1:DynamicPopulateExtender ID="DynamicPopulateExtender1" runat="server" BehaviorID="dp1" 
ClearContentsDuringUpdate="true" ServiceMethod="getName" TargetControlID="lblName" 
UpdatingCssClass="dynamicPopulate_Updating" />
    </form>
</body>

In this webform I have placed a DynamicPopulateExtender with BehaviorID="dp1"
which is passed to the Javascript function used for populating. ServiceMethod is
the webservice method written in code behind to get the value using contextKey
which holds the parameter value. TargetControlID contains the ID of the control
used for displaying the value.


C# Code (.aspx.cs) :


    protected void Page_Load(object sender, EventArgs e)
    {

    }

    [System.Web.Services.WebMethod]
    [System.Web.Script.Services.ScriptMethod]
    public static string getName(string contextKey)
    {
        System.Threading.Thread.Sleep(250);

        string ret = "";
        string connectionString = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
        DataSet ds = new DataSet();
        using (SqlConnection dbConnection = new SqlConnection(connectionString))
        using (SqlCommand dbCommand = new SqlCommand())
        {

            dbCommand.Connection = dbConnection;
            dbConnection.Open();
            dbCommand.CommandText = "select * from agents where AGN_ID="+Convert.ToInt32(contextKey);
            SqlDataAdapter dataAdapter = new SqlDataAdapter();
            dataAdapter.SelectCommand = dbCommand;
            dataAdapter.Fill(ds);
        }
        if (ds != null)
        {
            if (ds.Tables.Count > 0)
            {
                if (ds.Tables[0].Rows.Count > 0)
                {
                    ret = ds.Tables[0].Rows[0]["AGN_Name"].ToString();
                }
            }
        }
        return ret;
       
    }

ScriptMethod attribute has to be provided to the method in order to use it for
AJAX controls. Webservice method takes the ID from contextKey and get corresponding
name from the database. Return type of the method should be public static string.

Output is :




No comments:

Post a Comment