views:

177

answers:

1

Hi!

I want to execute JavaScript when document is ready without much syntax overhead. The idea is to use Site.Master and ContentPlaceholder:

<script type="text/javascript">
    $(document).ready(function () {
        <asp:ContentPlaceHolder ID="OnReadyScript" runat="server" />
    });
</script>

and in inherited pages just write plain code:

<asp:Content ID="Content3" ContentPlaceHolderID="OnReadyScript" runat="server">
    $("#Login").focus();
</asp:Content>

It works fine but Visual Studio complains and gives warnings.

Warning in master page is Expected expression at the line <asp:ContentPlaceHolder.

In inherited pages warning is Could not find 'OnReadyScript' in the current master page or pages.

I tried using Writer.Write in master page to render script tag and wrapping code:

<% Writer.Write(@"<script type=""text/javascript"">$(document).ready(function () {"); %>
<asp:ContentPlaceHolder ID="OnReadyScrit" runat="server" />
<% Writer.Write(@"});"); %>

but page rendering terminates after opening script tag is rendered. Html basically ends with

<script type="text/javascript">

How can I make it work?

A: 

This is a bug in Visual Studio's syntax highlighting.

Try

<%= @"<script type=""text/javascript"">$(document).ready(function () {" %>
<asp:ContentPlaceHolder ID="OnReadyScript" runat="server" />
<%= @"});" %>
SLaks
Same as with `Writer.Write` - rendering terminates after opening `script` tag. `$(document)...` does not get rendered. Looks like there is some kind of built-in protection from JavaScript injection in Asp.Net.
Konstantin Spirin