【问题标题】:Modify and add html from asp.net从 asp.net 修改和添加 html
【发布时间】:2016-12-08 09:10:19
【问题描述】:

我正在尝试从asp.net 代码隐藏向我的html 文档添加几个<img> 标签。我查看了Adding Html from Code Behind in Asp.net,它似乎是解决方案,但我不确定divcontrol.Controls.Add 如何确定它将开始添加html 的确切位置。据我所知,它位于 html 的末尾。我也找到了Write Html Markup from code behind in asp.net,但我也不知道怎么用。

这是我正在使用的html。如何添加我也包含的img 标签?:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Gallery</title>
    <script type='text/javascript' src='/jquery-11.0.min.js'></script>  
    <script type='text/javascript' src='theme-tiles.js'></script>
</head>
<body>
    <form id="form1" runat="server">
    <h2>Tiles - Justified</h2>
    <div id="gallery" style="display:none;">
    </div>

    <script type="text/javascript">

        jQuery(document).ready(function () {

            jQuery("#gallery").gallery({
                tiles_type: "justified"
            });

        });

    </script>
    </form>
</body>

</html>

这是我需要在&lt;div id="gallery"&gt;标签之间添加的&lt;img&gt;标签:

<img alt="img1"
    src="images/thumbs/tile1.jpg"
    data-image="images/big/tile1.jpg"
    style="display:none"/>
</a>

这是我用来添加html的代码:

HtmlGenericControl divcontrol = new HtmlGenericControl();
divcontrol.Attributes["class"] = "sxro sx1co";
divcontrol.TagName = "div";
pnlUserSearch.Controls.Add(divcontrol);
Label question = new Label();
divcontrol.Controls.Add(question); // add to the new div, not to the panel

【问题讨论】:

    标签: c# html asp.net


    【解决方案1】:

    如果您正在创建客户端 HTML(不是服务器控件),那么您可以创建一个 Literal,如下所示:

    <div id="gallery" style="display:none;">    
      <asp:Literal runat="server" ID="MyLiteral" />
    </div>
    

    然后,在你的代码隐藏中,设置

    MyLiteral.Text = "<whatever html you want>"
    

    我是按字面意思回答您的问题(没有双关语。)可能有更好的/其他方式来实现最终目标。将“普通”客户端 HTML 与 Web 表单混合可能会有点混乱。 Webforms 希望您按照自己的方式做所有事情。

    如果您的容器 div (gallery) 改为服务器控件,则可能更有意义。如果您希望添加多张图片,那么您可能需要的是 Repeater

    老实说,如果您的开发路径不是太远,最好还是看看 ASP.NET MVC。


    另一种方法:

    只需将图像本身作为服务器控件直接添加到标记中即可。

    <div id="gallery" style="display:none;">    
      <img runat="server" ID="MyImage" Visible="False"/>
    </div>
    

    如果你想在你的代码隐藏中显示它,

    MyImage.Src = "/image url";
    MyImage.Visible = true;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-04-19
      • 2021-07-13
      • 1970-01-01
      • 1970-01-01
      • 2017-05-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多