How to call javascript method in asp.net web appli

2020-04-11 09:48发布

问题:

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

protected void button1_Click(object sender,EventArgs e){
    //javascript function call ex.
    /*
    boolean b=the return of:
    <script type="text/javascript">
    function update() {
        var result = confirm("Do you want to delimit the record?")
        if (result) {return true;}
        else {
             return false;
        }
    }
    </script>
    */
}

how can i do such a thing? i want when user press yes return true and i know he pressed yes...can i do so?

回答1:

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.



回答2:

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.



回答3:

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?');" />


回答4:

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.