How do I dynamically set source of an IFrame?

2019-02-18 03:48发布

问题:

I have an IFrame embedding a youtube video. I want to create a textbox where user (admins) can paste a new src (URL) of video and the IFrame take the new source. Here is what I have so far:

protected void Edited_Click(object sender, EventArgs e)
    {
       // HtmlControl frame1 = (HtmlControl)this.FindControl("frame1");
        string url = TextBox1.Text;
        frame1.Attributes["src"] = url;

    }

And in the html code is the Iframe:

<div id="video">
    <iframe title="YouTube video player" runat="server" width="420" 
            frameborder="1" style="height: 265px; float: left; 
            text-align: center;" id="frame1" 
        name="frame1" align="middle"></iframe>
       <br />
       </div>

I don't set any src in the beginning but when I paste a URL in the textbox and hit the button, the Iframe doesn't displays anything.

回答1:

You need to do this on the client browser, not server-side. I would suggest something like:

// (Add inside script element in head of page html)

window.onload = function() {
    document.getElementById('<id of input>').onchange = function() {
        changeFrameUrl();
    }
};

function changeFrameUrl() {
        var inputVal = document.getElementById('<id of input>').value;
        document.getElementById('<id of iframe>').src = inputVal;
}

Hope this helps - it's off the top of my head though, so don't diss me if it doesn't work first time!



回答2:

Other responses don't answer the question, they provide an alternative. The question is how to set iFrame src from C#. I'll answer that here.

I'm all for "right tools for the job" and use that mantra a lot myself - but only when the other tools are "wrong". That hasn't been established here. Can someone provide a good technical reason why this should not be done in code-behind?

I think the issue @Pepys is experiencing might be due to something in the URL, which he hasn't provided yet. For example, maybe his URL includes ampersands or other characters which need to be escaped.

The following code works fine for me:

excelframe.Attributes["src"] =
  @"https://r.office.microsoft.com/r/rlidExcelEmbed?"
+ @"su=-0000000000"
+ @"&Fi=zzzzzzzzzzzz!111"
+ @"&ak=x%3d9%26x%3d9%26x%3d!zzzzzzzzzz"
+ @"&kip=1"
+ @"&AllowTyping=True"
+ @"&ActiveCell='sheet1'!C3"
+ @"&wdHideGridlines=True"
+ @"&wdHideHeaders=True"
+ @"&wdDownloadButton=True";