Registering javascript on asynchronous postback

Go To StackoverFlow.com

0

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.

2012-04-03 20:49
by Jagd


2

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 });");
2012-04-03 20:51
by Darin Dimitrov
How about typeof($) != 'undefined' - ShankarSangoli 2012-04-03 20:56
@ShankarSangoli, good point. I have updated my answer to take it into account into the test of jQuery - Darin Dimitrov 2012-04-03 20:57
@Darin - Thank you so much! This did the trick - Jagd 2012-04-03 21:53