简体   繁体   中英

Can't get Javascript to fire from c# codebehind

I have read many posts here and many other sites and so I've gathered a few versions of HOW to do this. My problem is that I can't get it to do anything.

Here's the Javascript, just an alert for testing:

    <script type="text/javascript">
        function ICDcheck() {
                alert('Patient has an ineligible diagnosis code!');
        }
    </script>

I tested this manually by adding the function to an OnClientClick of a button and it worked fine.

Here is what I've tried in the codebehind:

ClientScript.RegisterClientScriptBlock(this.GetType(), "uniqueKey", "ICDcheck()", true);

and...

    string jsMethodName = "ICDcheck()";
    ScriptManager.RegisterClientScriptBlock(this, typeof(string), "uniqueKey", jsMethodName, true);

and...

    lblJavaScript.Text = "<script type='text/javascript'>ICDcheck();</script>";

This last one references a label I have sitting at the top of my asp : Content just below a script and the asp : ScriptManager block.

I've placed these bits in the button_click, the page_load, the sqldatasource_selecting, the formview_PageIndexChanging and always the same, nothing.

As always, thanks for your patience and help. My ignorance will likely be exposed as the problem, but I'm learning.

Try using Page.ClientScript :

Page.ClientScript.RegisterStartupScript( GetType(), "MyKey", "ICDcheck();", true);

Also install firebug and check if there are any script errors.

Try this. On your page, have a button:

<asp:Button ID="RunJsButton" runat="server" Text="Button" />

Then, in the code-behind, inject the script into the response and add the wireup to the button:

    protected void Page_Load(object sender, EventArgs e)
    {
        string scriptToRun = @"function ICDcheck() { alert('Patient has an ineligible diagnosis code!');}";

        ClientScript.RegisterClientScriptBlock(this.GetType(), "", scriptToRun, true);
        RunJsButton.OnClientClick = "return ICDcheck();";
    }

If that is the kind of thing you are after, you can refactor it a bit to implement best practice.

Try

<button ID="your_btn" onclick="javascript:your_function(); return false;"><asp:literal ID="your_literal" runat="server" /></button>

and

<script type="text/javascript">
    function your_function() {
            alert('Patient has an ineligible diagnosis code!');
    }
</script>

This should work.

string jsToRun = "<script language=javascript>ICDcheck();</script>";

Type csType = this.GetType();

ClientScript.RegisterStartupScript(csType, "Key", jsToRun);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM