how to call codebihind function in javascript

Last post 02-15-2008 6:49 AM by Vince Xu - MSFT. 3 replies.

Sort Posts:

  • how to call codebihind function in javascript

    02-14-2008, 5:38 AM
    • Member
      point Member
    • santhosh.mm
    • Member since 02-08-2008, 9:46 AM
    • Posts 11

    how to call codebihind function in javascript

     i have used in following function in codebihind page.

    how to call the function in my java script function. 

    public void inserting()

    {

    if( TextBox1.Text!= "")

    {

    strvalidate=Convert.ToInt32(TextBox1.Text.Substring(2,1));

    }

    if (strvalidate ==1)

    {

    String strins;

    DateTime dt;

    dt=Convert.ToDateTime(ddldate.SelectedItem.Text);

     

    strins= "insert into dailyentry(projectid,description,trackerdate,hrsplanned,starttime,endtime,timescoverd,userid)";

    strins=strins +"values('"+ ddlProjectName.SelectedItem.Value +"','"+ txtDescription.Text +"','"+ dt.ToString("yyyyMMdd") +"','"+ txtHoursPlanned.Text+"','"+txtStart.Text+"','"+txtEnd.Text+"','"+TimeCoverd.Text+"','EM0002')";

    cmddaily=
    new SqlCommand(strins,Connections.MyConn);

    cmddaily.ExecuteNonQuery();

     

    binddata();

    }

     

    }

  • Re: how to call codebihind function in javascript

    02-14-2008, 8:43 AM
    • Contributor
      5,452 point Contributor
    • CSharpSean
    • Member since 10-21-2006, 5:43 AM
    • Orlando, FL
    • Posts 915

    Hello,

     You can use 'Page Methods'. Check out the following links for more details:

    http://www.singingeels.com/Articles/Using_Page_Methods_in_ASPNET_AJAX.aspx

    http://fredrik.nsquared2.com/viewpost.aspx?PostID=393

     

    Hope this helps. 

  • Re: how to call codebihind function in javascript

    02-14-2008, 10:35 AM
    Answer
    • Contributor
      5,452 point Contributor
    • CSharpSean
    • Member since 10-21-2006, 5:43 AM
    • Orlando, FL
    • Posts 915

    An Example:

    ASPX: 

     

       <asp:ScriptManager id="ScriptManager1" runat="server" EnablePageMethods="true">
          <Scripts>
            <asp:ScriptReference Path="script.js" />
          </Scripts>
        </asp:ScriptManager>
        
        State Name: <asp:TextBox ID="txtName" runat="server" /><br />
        State Abbr: <asp:TextBox ID="txtAbbr" runat="server" /><br />
        <asp:Button ID="btnInsert" runat="server" Text="Insert" Width="237px" />
     
    Code Behind: 
     
     protected void Page_Load(object sender, EventArgs e)
        {
    			btnInsert.Attributes.Add("onclick", "javascript:InsertState('" + txtName.ClientID + "', '" + txtAbbr.ClientID + "')");
        }
    
    	[System.Web.Services.WebMethod]
    	public static string InsertState(string name, string abbr)
    	{
    		try
    		{
    			using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["CarrierDBConnectionString"].ConnectionString))
    			{
    				using (SqlCommand cmd = new SqlCommand("INSERT INTO STATE ([NAME],[ABBR]) VALUES (@NAME, @ABBR); SELECT SCOPE_IDENTITY()",conn))
    				{
    					cmd.CommandType = CommandType.Text;
    					cmd.Parameters.AddWithValue("@NAME", name);
    					cmd.Parameters.AddWithValue("@ABBR", abbr);
    
    					conn.Open();
    
    					return cmd.ExecuteScalar().ToString();
    				}
    			}
    		}
    		catch (Exception ex)
    		{
    			throw new Exception("Error Inserting Record! " + ex.Message);
    		}
    	}
      
    JavaScript File:
      
          function InsertState(nameCtrl, abbrCtrl){
            var name = $get(nameCtrl).value;
            var abbr = $get(abbrCtrl).value;
            PageMethods.InsertState(name, abbr, OnSucceeded, OnFailed);
          }     
          
          function OnSucceeded(res){
            alert('Record Inserted! Record Number: ' + res);
          }
          
          function OnFailed(error){
            alert(error.get_message());
          }
     
     
    Hope this helps =) 
      
  • Re: how to call codebihind function in javascript

    02-15-2008, 6:49 AM
    Answer

    Hi,

    There are two approach for achieving it.

    1. <%inserting();%> : Put this code into HTML not JavaScript, and it will execute this function.

    2. Use doPostBack in JavaScript to trigger a function in CodeBehind.

    For example, there is a control Text1.When mouseup will trigger doPostBack:

    <input id="Text1" type="text" onmouseup="javascript:__doPostBack('Text1','onmouseup')"/>

     Code Behind:

    In Page_Load, it needs to retrieve the doPostBack.

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.Params["__EVENTTARGET"] != null)
            {
                string target = Request.Params["__EVENTTARGET"].ToString();

                string passedArgument = Request.Params["__EVENTARGUMENT"].ToString();
                if (target == "Text1" && passedArgument == "onmouseup")
                {
                      inserting();
                }
            }
        }

    Hope it helps.

     


    Vince Xu
    Microsoft Online Community Support
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.
Page 1 of 1 (4 items)