-2

How do you call a JavaScript function behind C#? I have a button that I created and there's C# code behind to execute specific tasks, but I also want to add JavaScript function, where it changes the action when the button it is fired.

Here is the JavaScript function,

  function myFunction()
  {
      document.getElementByID("Form").action="/submit.aspx";
  }

Here is my C# code for the button:

protected void btnSubmit_Click(object sender, EventArgs e)
{
}
Alper
  • 12,860
  • 2
  • 31
  • 41
user3813162
  • 47
  • 2
  • 10
  • 1
    Please clarify the interaction/interop in your application between C# and Java. I don't understand the question. – Jashaszun Aug 01 '14 at 17:56
  • This is question that can be googled. There are many readily available answer via google. And even some within stackoverflow http://stackoverflow.com/questions/5731224/calling-javascript-function-from-codebehind. – TYY Aug 01 '14 at 17:57
  • Why not use OnClientClick to call your java script function directly? – Pat Hensel Aug 01 '14 at 18:01
  • I'm here to ask for help. Not for your negative feedbacks. Don't you think I've tried looking at other questions in Stack Overflow or even Google it before asking this question? Pat- I want to execute my C# code before JavaScript, I've tried that but it didn't work for me. – user3813162 Aug 01 '14 at 18:31

1 Answers1

0

Use Page.ClientScript.RegisterStartupScript see sample code below:

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        //place c# code here that does something before your javascript

        Page.ClientScript.RegisterStartupScript(this.GetType(), "CallMyFunction", @"$(document).ready(function() {
                //Call your function here
                myFunction();
            });", true);
    }

Note, my code uses jQuery, modify as needed. I hope this helps you.

Simua
  • 263
  • 1
  • 10
  • You don't have to use it in the if statement, do you? – user3813162 Aug 01 '14 at 20:03
  • no you don't have to use it in the if statement, I have edited the code – Simua Aug 01 '14 at 20:07
  • Let me know if you have any issues, I sure would like to help – Simua Aug 01 '14 at 20:50
  • Thanks, I appreciate the help. I will let you know how it goes. – user3813162 Aug 01 '14 at 21:02
  • It's not working for me in Dot Net Nuke. It worked fine with regular ASP.NET with C#. I will try an alternative way. How would you add a message box after a file is completed upload? Can you provide me with an example? – user3813162 Aug 01 '14 at 21:19
  • protected void btnSubmit_Click(object sender, EventArgs e) { //place c# code here that does something before your javascript Page.ClientScript.RegisterStartupScript(this.GetType(), "CallMyFunction", @"$(document).ready(function() { //Call your function here alert('File Uploaded Successfully!'); //this line });", true); } – Simua Aug 01 '14 at 21:25