简体   繁体   English

使用C#动态地将HTML添加到ASP.NET页面

[英]Dynamically adding HTML to ASP.NET page with C#

I'm trying to create a simple store locator on an ASP.NET page. 我正在尝试在ASP.NET页面上创建一个简单的商店定位器。 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. 我让用户输入他们的邮政编码,然后C#用它创建一个变量并将其附加到网址的末尾,以便在他们附近的Google地图上搜索该商店。 I then need it to dynamically add an iframe tag with it's source as that url to the page. 然后我需要它动态添加一个iframe标记,其源代码为该页面的url。

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. 您实际上可以将runat="server"添加到ASP.NET webforms中页面上的任何标准HTML标记。 Try this on your page: 在您的页面上试试这个:

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

This will give you access to your iframe by name in code behind. 这样,您就可以在代码后面按名称访问iframe。 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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