Nalaka
Nalaka

Reputation: 109

iframe error when runat="server"

I have a iframe in one of my web pages with runat="server" and a javascript function assigned to the onload event.
When the page renders it gives an error as
"CS1012: Too many characters in character literal"
When I remove the runat="server" attribute it works perfectly but I need the iframe to runat="server".
How can I fix this?

<iframe id='contentFrame' name='contentFrame' 
   runat="server" width="500"
   onload="resizeFrame(document.getElementById('contentFrame'))">
 </iframe>

Upvotes: 4

Views: 8056

Answers (5)

Philipp Munin
Philipp Munin

Reputation: 5903

When you use runat="server" - 'onload' starts being parsed as C# Event of Html Server Control, like Button.Click. You should set a name of C# event handler method in the class of your control/page (NOT JAVASCRIPT). This code will work:

<script runat="server">
    void contentFrame_onLoadServer(object sender, EventArgs e)
    {
        if (!IsPostBack)
            contentFrame.Attributes.Add("onLoad", "contentFrame_onLoadClient();");
    }
</script>
<script type="text/javascript">
    function contentFrame_onLoadClient() {
        resizeFrame(document.getElementById('<%=contentFrame.ClientID %>'));
    }
    function resizeFrame(element) {
        alert(element); // do your logic here
    }
</script>
<iframe 
    runat="server" 
    id='contentFrame' 
    name='contentFrame' 
    width="500" 
    onload="contentFrame_onLoadServer"
    />

Upvotes: 14

Grimace of Despair
Grimace of Despair

Reputation: 3506

You cannot "just" add the onload for client side code, because it's "occupied" by the .NET server side onload. You need to hook it up by code (and I enhanced @Philipp 's code):

<script runat="server">
void onIframeLoad(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        contentFrame.Attributes.Add("onload", "resizeFrame(document.getElementById('contentFrame'));");
    }
}
</script>
<iframe id='contentFrame' 
    name='contentFrame' 
    runat="server" width="500" 
    onload="onIframeLoad"/>

Upvotes: 1

user1509
user1509

Reputation: 1161

runat="server" changes the ID of the IFrame.

instead of passing "document.getElementById('contentFrame')" pass "this" in javascript.

Or you may also pass

document.getElementById('<%= contentFrame.ClientID%>')

Upvotes: 0

Azhar Mansuri
Azhar Mansuri

Reputation: 705

You can not write document.getElementById('contentFrame') in onload method. Write it in your javascript function instead.

Upvotes: 0

Zaheer Ahmed
Zaheer Ahmed

Reputation: 28588

replace single quotation with double:

< iframe id="contentFrame" name="contentFrame" runat="server" width="500" onload="resizeFrame(document.getElementById('contentFrame'))">

Upvotes: 0

Related Questions