简体   繁体   中英

Call javascript function defined in html page from aspx.cs page

I have an HTML page and an .aspx page in my project. I defined a javascript function in the html page and trying to call it from code behind of the .aspx page

I tried using ClientScript.RegisterStartupScript() and ScriptManager.RegisterStartupScript() as following.

HTML page - MainPage.html

<script type="text/javascript">
    $(document).ready(function () {
        function functionName() {
            #content
        };
    });
 </script>

.aspx page - form.aspx.cs

Try 1

protected void Button2_Click(object sender, EventArgs e)
{
    ScriptManager.RegisterStartupScript(this, GetType(), "MainPage.html", "functionName();", true);
}

Try 2

protected void Button2_Click(object sender, EventArgs e)
{
    ClientScript.RegisterStartupScript(GetType(), "Javascript", "javascript:functionName(); ", true);
}

I am trying to call function functionName() from HTML page when Button2 from aspx page was clicked

I don't have rights to comment your question to ask for clarification, so I'm going out on a limb, here. Apologies if I miss something.

Would you be able to put the jQuery code from your extract in a js script file, and include it both in your Html page and in your aspx page?

Then, you could manage the button click in your aspx page on the client side, without sending it back to the server (if your button click doesn't do anything on the server, other than registering the js code)

Something like this:

<script type="text/javascript">
    $(document).ready(function () {
        $('#yourButtonId').on('click', function (e) {
            e.preventDefault(); // this prevents the form to be submitted to the server
            functionName(); // Execute your function
        });
    });
 </script>

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