Thursday, August 2, 2012

Insert/Show Record Using Client Callbacks in asp.net

Client callbacks : Rather than posting back the entire page, your custom control can send a request to the server to get just the additional information it needs.

Example:                                                        On Click of Button Insert Record in Database with text value.

 in .aspx page                                                             <script type="text/javascript">
        function ss() {
            var va = document.forms[0].Text1.value;
            UseCallback(va, "");
      
    
        }
        function show(Text1, context) {
            alert(Text1);
      
        }
    </script> 
      <asp:Panel ID="Panel2" runat="server">
      <input id="Text1" type="text" runat="server" />
      <input id="Button1" type="button" value="button" onclick="ss()"/>
     <asp:UpdatePanel ID="UpdatePanel1" runat="server">
     <Triggers>
      <asp:AsyncPostBackTrigger ControlID="Timer1" EventName="Tick" />
     </Triggers>
     <ContentTemplate>
     <asp:Timer ID="Timer1" runat="server" Interval="1000">
     </asp:Timer>
     <asp:DropDownList ID="DropDownList1" runat="server">
     </asp:DropDownList>
     </ContentTemplate>
     </asp:UpdatePanel>
    </asp:Panel>

   in .cs page                              
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
  
 public partial class _Default: System.Web.UI.Page, System.Web.UI.ICallbackEventHandler
{
    SqlConnection con = null;
    SqlCommand cmd,cmd1 = null;
    DataSet ds = null;
    SqlDataAdapter da = null;
    private string aa = null;
  protected void Page_Load(object sender, EventArgs e)
    {
        string cref = Page.ClientScript.GetCallbackEventReference(this, "arg", "show", "context");
        string cscript = "function UseCallback(arg,context)" +
            "{" + cref + ";" + "}";
        Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "UseCallback", cscript, true);



 cmd1 = new SqlCommand("select Message from ChatDb", con);
      da = new SqlDataAdapter(cmd1);
      ds = new DataSet();
      da.Fill(ds);
      if (ds.Tables[0].Rows.Count > 0)
      {
        
          DropDownList1.DataSource = ds.Tables[0];
          DropDownList1.DataTextField = "Message";
          DropDownList1.DataBind();
      }
    } 
  public string GetCallbackResult()
    {
        return aa;
    }
    public void RaiseCallbackEvent(string eventArgument)
    {

 cmd = new SqlCommand("insert into ChatDb values('" + eventArgument + "')", con);
        con.Open();
        cmd.ExecuteNonQuery();
        con.Close();


        aa = eventArgument;
    } 
}
OutPut

 

No comments:

Post a Comment