Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Executing JavaScript on a Button Click in Code Behind [duplicate]

Tags:

c#

asp.net

Possible Duplicate:
How to call javascript function from c#

Is there a way to call a javascript function from a button click in code behind in C#? So basically I have a registration form and when you click the button, then all the data is processed in the code behind and the form is submitted. But I need to execute some javascript and I need it to be executed on the button click and in code behind.

so something like:

    protected void btnDoRegister_Click(object sender, System.Web.UI.ImageClickEventArgs e)
    {
         C# code is here doing form processing
         // Now I need to Execute javascript here.
    }

Is this possible and how would I go about doing it, if it is?

Thanks!


2 Answers

protected void btnDoRegister_Click(object sender, System.Web.UI.ImageClickEventArgs e)
{
     C# code is here doing form processing
     // Now I need to Execute javascript here.
     string script = "<script type=\"text/javascript\"> functionToExecute(); </script>";
     ClientScript.RegisterClientScriptBlock(this.GetType(), "myscript", script);
}
like image 169
codingbiz Avatar answered Nov 30 '25 22:11

codingbiz


Executing javascript on server is not possible as javascript executes on client(browser). You can execute javascript after postback but it is seldom required. Normally Javascript executes on client side and executes before the request is received at server and executed on server. This way you have two event binded with btnDoRegister one executes on client and ohter executes on server.

On Page_Load bind javascript event with button.

In Code Behind

btnDoRegister.Attributes.Add("onclick", "funForButton();");

In aspx HTML

<script language="javascript" type="text/javascript">     
function funForButton()
{
   alert("About to send request to server");
}

</script>

The Server event you already have

protected void btnDoRegister_Click(object sender, System.Web.UI.ImageClickEventArgs e)
{
     C# code is here doing form processing
     // Now I need to Execute javascript here.
}
like image 30
Adil Avatar answered Nov 30 '25 20:11

Adil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!