Yulia V
Yulia V

Reputation: 3559

How to call javascript function and c# code on asp:button?

When a user clicks a button on ASP.net page, I need to

  1. Save file from asp:fileUpload in a folder on a server - I guess this needs to be done in C#, like in How to correctly use the ASP.NET FileUpload control

  2. Run a javascript function like in How to call javascript function from asp.net button click event

Is there a way to combine C# and Javascript to achieve what I need? If not, how should I do it?

Upvotes: 0

Views: 15079

Answers (2)

drigoangelo
drigoangelo

Reputation: 127

Try using the onClientClick property of the asp:button element.

Ex, on your .aspx file:

<script type="text/javascript">
  function myFunction()
  {
    alert('hi');
  }    
</script>
...

<asp:button id="Button1"
   usesubmitbehavior="true"
   text="Open Web site"
   onclientclick="myFunction()"
   runat="server" onclick="Button1_Click" />

And in your code behind (.aspx.cs)

  void Button1_Click (object sender, EventArgs e)
  {
    if (this.FileUpload1.HasFile)
    {
        this.FileUpload1.SaveAs("c:\\" + this.FileUpload1.FileName);
    }

  }

More info at

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.button.onclientclick.aspx

Upvotes: 4

David
David

Reputation: 218827

Note that no JavaScript actually "runs" until the server-side code (C# in this case) has entirely completed and the resulting page is returned to the client. Once that page renders on the client, then JavaScript runs on the client.

So in order to execute your JavaScript code, all you need to do is include it in the page being returned to the client. There are a number of ways to do this, and the options depend on whether you're using WebForms or MVC.

You might use something like RegisterStartupScript in WebForms, for example. Or, you could just have the JavaScript code exist in a PlaceHolder control with Visible=false and only make the control visible in the response which intends the JavaScript code to run. (Roughly the same method is also easily usable in MVC by just wrapping the JavaScript code in a server-side condition to determine whether to render it or not.)

The main thing to remember is that you're not "running the JavaScript code from C#" or anything like that. There's a hard separation between server-side and client-side code. The server-side code ultimately builds the page that it sends back to the client, and that page can include JavaScript code to run on that client.

Upvotes: 2

Related Questions