javascriptjqueryasp.netasynchronous-postback

Registering javascript on asynchronous postback


I have an asp.net button wrapped inside of an UpdatePanel, and when clicked it does an asynchronous postback and registers some javascript that shows a jquery dialog.

protected void btnAddData(object sender, EventArgs e) {
    StringBuilder jqueryDialog = new StringBuilder();
    jqueryDialog.Append("$(document).ready(function() {");
    jqueryDialog.Append("RefreshData();");
    jqueryDialog.Append("$('#divData').dialog({ modal: false, draggable: true, title: 'Historical Data', width: 700 });");
    jqueryDialog.Append("});");

    ScriptManager sm = ScriptManager.GetCurrent(this);
    if (sm != null && sm.IsInAsyncPostBack) {
        ScriptManager.RegisterClientScriptBlock(
            this, typeof(Page), Guid.NewGuid().ToString(),
            jqueryDialog.ToString(), true);
    }
}

As you can see the javascript first calls a function named RefreshData(), which function exists in my markup as javascript.

<script type="text/javascript" language="javascript">
    if ($) {
        $(document).ready(function () {
            function RefreshData() {
                alert("Data Refreshed!");
            }
        });
    }
</script>

However, Firefox is giving an error that says the RefreshData is not defined. Does that mean any javascript that I register on an asynchronous postback will be unable to use javascript functions that I have defined in my markup?

Thanks for the help.


Solution

  • Don't define the RefreshData function inside the document.ready function which is an anonymous callback. Define it outside so that it is accessible to the outside:

    <script type="text/javascript">
        if (typeof($) != 'undefined') {
            function RefreshData() {
                alert("Data Refreshed!");
            }
        }
    </script>
    

    Also you probably don't need to wrap in a document.ready your server side include:

    StringBuilder jqueryDialog = new StringBuilder();
    jqueryDialog.Append("RefreshData();");
    jqueryDialog.Append("$('#divData').dialog({ modal: false, draggable: true, title: 'Historical Data', width: 700 });");