asp.net后台动态生成前台布局(转)

 

今天做一个商品搜索页面的时候,需要从数据库读取一些商品信息绑定到前台页面,由于在前台已经布局好了,没有用到GridView控件,所有数据都是动态地绑定到一个<div>里面的,因此需要在后台动态地添加一些控件。在网上参考了一些资料,主要是通过Controls容器实现。原理就不说了,直接写出一些操作的方法

前台代码:

<div>

<ul id="tryul" runat="server">

</ul>

</div>

后台代码:

Label label1=new Label();

label1="测试";

tryul.Controls.Add(newLiteralControl("<li>"));//添加<li>标签

tryul.Controls.Add(label1);//嵌套<li>标签里面的内容太

tryul.Controls.Add(newLiteralControl("</li>"));

通过这样的就可以简单的实现在<ul>标签里插入<li>标签了

其他的标签用同样的方法可以动态生成,下面贴出我代码里的一些后台代码,供参考

Label productName = new Label();
        Label productCost = new Label();
        Label productFreight = new Label();
        Label ProductSite = new Label();
        ProductSite.Text = "广州";
        productFreight.Text = "10";
        productCost.Text = "10000";
        productName.Text = @"<a href='product1.aspx'>Windows Vista正版</a>";
        Image img = new Image();
        img.ImageUrl = "images/product/20418275-1_t.jpg";
        img.Height = 80;
        img.Width = 80;
        productul.Controls.Add(new LiteralControl("<li>"));
        productul.Controls.Add(new LiteralControl("<div id=\"productImage\">"));
        productul.Controls.Add(img);
        productul.Controls.Add(new LiteralControl("</div>"));
        productul.Controls.Add(new LiteralControl("<strong>"));
        productul.Controls.Add(new LiteralControl("<div id=\"productName\">"));//产品名
        productul.Controls.Add(new LiteralControl("<div class=\"margintop20\">"));
        productul.Controls.Add(productName);
        productul.Controls.Add(new LiteralControl("</div>"));
        productul.Controls.Add(new LiteralControl("</div>"));
        productul.Controls.Add(new LiteralControl("<div id=\"productCost\">"));//价格
        productul.Controls.Add(new LiteralControl("<div class=\"margintop30\">"));
        productul.Controls.Add(productCost);
        productul.Controls.Add(new LiteralControl("</div>"));
        productul.Controls.Add(new LiteralControl("</div>"));
        productul.Controls.Add(new LiteralControl("<div id=\"productFreight\">"));//运费
        productul.Controls.Add(new LiteralControl("<div class=\"margintop30\">"));
        productul.Controls.Add(productFreight);
        productul.Controls.Add(new LiteralControl("</div>"));
        productul.Controls.Add(new LiteralControl("</div>"));
        productul.Controls.Add(new LiteralControl("<div id=\"productSite\">"));//产地
        productul.Controls.Add(new LiteralControl("<div class=\"margintop30\">"));
        productul.Controls.Add(ProductSite);
        productul.Controls.Add(new LiteralControl("</div>"));
        productul.Controls.Add(new LiteralControl("</div>"));
        productul.Controls.Add(new LiteralControl("</strong>"));
        productul.Controls.Add(new LiteralControl("</li>"));

因为时间关系,也没有细细地研究更多的用法,懂得更多的朋友欢迎指点

posted @ 2010-11-30 11:41  简单飞翔  阅读(1225)  评论(0编辑  收藏  举报