Tuesday, October 4, 2011

jQuery modal alert in Page_Load

To insert a jQuery alert into Page_Load method of an our WebForm (maybe for a bad result of an operation) could not be simple, 'cause Page_Load method is invoked before thar the page loads included script files.

To solve it, just do this:

Protected Sub Page_Load(sender As Object, e As System.EventArgsHandles Me.Load

ScriptManager.RegisterClientScriptInclude(Page, Page.GetType, Guid.NewGuid().ToString(), Page.ResolveUrl("~/js/jquery-1.6.2.min.js"))
        ScriptManager.RegisterClientScriptInclude(Page, Page.GetType, Guid.NewGuid().ToString(), Page.ResolveUrl("~/js/jquery-ui-1.8.16.custom.min.js"))
        Dim sb As New StringBuilder
        sb.Append("$(function() { ")
        sb.Append(" $( '#dialog-message-error' ).dialog({")
        sb.Append("    modal: true,")
        sb.Append("    buttons: {")
        sb.Append("        Ok: function() {")
        sb.Append("               $( this ).dialog( 'close' );")
        sb.Append("        }")
        sb.Append("    }")
        sb.Append(" });")
        ScriptManager.RegisterClientScriptBlock(Page, Page.GetType, Guid.NewGuid().ToString(), sb.ToString, True)
End Sub

It's supposed to have jquery and jquery-ui script files into the "js" folder on application root, and that this div exists:

<div id="dialog-message-error" title="Error" style="display: none; font-size: small">
<div class="ui-state-error ui-corner-all" style="padding: 0 .7em;">
<span class="ui-icon ui-icon-alert" style="float: left; margin-right: .3em;">span>
<strong>Error:strong> Error text....

No comments: