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

时间:2013-08-06 18:00:02

标签: c# html asp.net

我试图在ASP.NET页面上创建一个简单的商店定位器。我让用户输入他们的邮政编码,然后C#用它创建一个变量并将其附加到网址的末尾,以便在他们附近的Google地图上搜索该商店。然后我需要它动态添加一个iframe标记,将其作为该网址的源代码添加到页面中。

类似的东西:

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

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);

}

我相信它是正确的,直到最后一行,任何想法?

1 个答案:

答案 0 :(得分:2)

您实际上可以将runat="server"添加到ASP.NET webforms中页面上的任何标准HTML标记。在您的页面上试试这个:

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

这样,您就可以在代码后面按名称访问iframe。然后,您可以通过编写如下语句来操纵事物:

MyIframe.Visible = true;

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