简体   繁体   中英

Dynamically adding HTML to ASP.NET page with C#

I'm trying to create a simple store locator on an ASP.NET page. I have the user enter their zipcode, then C# creates a variable with it and appends it to the end of a url to search for that store on Google maps near them. I then need it to dynamically add an iframe tag with it's source as that url to the page.

Something like:

<asp:TextBox ID="TextBox1" placeholder="Zip code" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Find locations" onclick="Button1_Click" />

And:

protected void Button1_Click(object sender, EventArgs e)
{
    var zipCode = TextBox1.Text;

    HtmlGenericControl iframe = new HtmlGenericControl();
    iframe.ID = "iframe";
    iframe.TagName = "iframe";
    iframe.Attributes["class"] = "container";
    iframe.Attributes["src"] = "https://www.google.com/maps/preview#!q=gnc+near%3A+" + zipCode;
    this.Add(iframe);

}

I believe it's correct until the last line, any thoughts?

You can actually add runat="server" to any standard HTML tag on the page in ASP.NET webforms. Try this on your page:

<iframe id="MyIframe" runat="server"></iframe>

This will give you access to your iframe by name in code behind. You'll then be able to manipulate things by writing statements like:

MyIframe.Visible = true;

and

MyIframe.Attributes.Add("src", "https://www.google.com/maps/preview#!q=gnc+near%3A+" + zipcode);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM