How to call javascript method in asp.net web application

前端 未结 4 1357
无人及你
无人及你 2021-01-21 01:26

I want to use a javascript function inside a c# function

protected void button1_Click(object sender,EventArgs e){
    //javascript function call ex.
    /*
    b         


        
相关标签:
4条回答
  • 2021-01-21 01:44

    If you're putting this message on an <asp:Button> with postback just add the confirm dialog to the OnClientClick attribute like so:

    <asp:Button ID="Button1" runat="server" 
        OnClientClick="return confirm('Do you want to delimit the record?');" />
    
    0 讨论(0)
  • 2021-01-21 01:45

    If you're simply trying to create the functionality of letting the server know that a button was clicked, you're over complicating things. If you really need to dynamically insert Javascript then what Adam mentioned is worth looking into. But I highly doubt that this is the correct approach for what you're trying to do.

    You should really only dynamically insert Javascript when you're worried about performance AND you have a lot of content to send.

    If dynamically inserting Javascript (ie. lazy loading) is not your main concern, then here is a very simple example of what most folks would usually do to achieve the functionality you're aiming for.

    0 讨论(0)
  • 2021-01-21 02:00

    If you're trying to add JavaScript to your page from asp.net, you can use the ClientScript class.

    string script = "function update() { var result = confirm(\"Do you want to delimit the record?\") if (result) {return true; } else { return false; } }";
    ClientScript.RegisterClientScriptBlock(this.GetType(), "someKey", script, false);
    

    If you're trying to call (client side) JavaScript functions from your asp.net code behind, then absolutely not. When the page posts and your C# is run, any JavaScript that was on the page no longer exists.

    0 讨论(0)
  • 2021-01-21 02:00

    You're mixing two different technologies. C# runs on the server. It renders an HTML page (which may include Javascript). This page is then sent to a client's browser, where Javascript finally gets executed.

    In Javascript you can prompt user about record deletion or whatever, and then you have to either navigate to another page or use AJAX to send result to the server.

    I suggest that you get a good ASP.NET book. It will clear many uncertainties for you.

    0 讨论(0)
提交回复
热议问题