Search code examples
javascriptcode-behind

Why would there be a need to call a JavaScript function from code behind?


I just been looking around online about calling a JavaScript function from code behind, from examples that I have seen you RegisterStartupScript method on a click event. But why would you want or need to do that instead of just wiring it up the OnClientClick event? Is there ever a need to call a JavaScript function from code behind?


Solution

  • RegisterStartupScript is one of many options for an infinite number of scenarios. In the end, anything you can do with RegisterStartupScript can be done another way. I used to consider it a convenience, now I avoid it, separation of concerns and such higher stages of "enlightenment".

    Mainly where I see RegisterStartupScript still in use is with custom controls that are expected to wire themselves up without the end-user knowing anything about them. See AjaxControlToolKit, UpdatePanel, ScriptManager, etc. They all require javascript but for obvious reasons do not expect you to include their client-side scripts or register them.

    Random Scenario:

    if (User.Identity.Name == "Frank")
        RegisterStartupScript(this, GetType(), "Frank", "alert("Hey Frank, you owe me money!");
    

    Alternative Scenario, have the server-side set a hidden field.

    <input type="hidden" id="name" value="<%= User.Identity.Name %>" />
    
    <script type="text/javascript">
        $(document).ready(function() {
            if ($("#name").val() == "Frank")
                alert("Hey Frank, you owe me money!");
        });
    </script>