RegisterClientScriptBlock code not executing
I'm using the following code in an attempt to show a dialog with a list of errors on the client:
if (rollout.ImportErrors.Count > 0)
{
ClientScript.RegisterClientScriptBlock(GetType(), "showErrors", "showErrors();", true);
}
The error count is non-zero and the following script block is emitted, but the script isn't executing.
<script type="text/javascript">
//<![CDATA[
$("#error-report").dialog("open")//]]>
</script>
If I call the function directly from a Firebug console window, the dialog shows properly, so I know the dialog and my code are working. What am I doing wrong?
BTW, this code is in a content page, using 开发者_JS百科a content placeholder that 'injects' code into the element of the rendered page.
I think you should try RegisterStartupScriptBlock instead of RegisterClientScriptBlock...
Check out the explanation:
RegisterClientScriptBlock inserts the script immediately following the start tag whereas RegisterStartupScript adds the script immediately before the end tag.
In IE the HTML DOM is created in a serial fashion. So your header information will be processed first your form object will be created, your RegisterClientScript will be parsed (and executed if not in function blocks) your controls such as textboxes etc in your form will be created, then your RegisterStartupScript will be parsed (and executed if not in function blocks).
So, in IE at least, you are basically guaranteed that any form elements will exist for your scripts to access if you put the code in the RegisterStartupScript. Conversely, you are basically guaranteed that any form elements will not exist for your scripts in the RegisterClientScript block and the code is not in function blocks.
You need to wrap it in this case, like this:
$(function() { $("#error-report").dialog("open"); });
It's just placing it in the page, but the DOM may still not be ready (it is when you run it in the console, that's why it works there). Like you would writing script directly in the page, wrap it so it doesn't execute until document.ready
.
You can have a look at it http://www.jdxyw.com/?p=411
精彩评论