zoukankan      html  css  js  c++  java
  • 动态加载并获取usercontrol生成的html

        在项目中用户控件往往是html代码的生成工具,在aspx页面中添加其引用就可以获取它所生成的html代码

        以供显示。但如何在后台代码.cs文件中动态的加载并获取其html代码就不容易了,以下是我研究的心得。

        方案一: 在用户控件中添加公共属性和公共方法以供外部程序调用。

    ddl.ascx.cs code:

    public
    partial class ddl : System.Web.UI.UserControl { public List<string> sourceList { get; set; } //公共属性 public void setValue() //公共方法 { List<string> currentSource = this.sourceList; foreach (string str in currentSource) { ListItem item = new ListItem(); item.Value = str; item.Text = str; _ddl.Items.Add(item); } } }
     
    userControlTest.aspx.cs code:

    protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { List<string> testList=new List<string> (); testList.Add("xiaochun"); testList.Add("xiaochun"); testList.Add("xiaochun"); testList.Add("xiaochun"); testList.Add("xiaochun"); StringWriter sw = new StringWriter(); HtmlTextWriter writer = new HtmlTextWriter(sw); UserControl userControl = new UserControl(); string pathString = "/usercontrol/ddl.ascx"; //注意这里不能为绝对路径 ddl currentControl= userControl.LoadControl(pathString) as ddl; currentControl.sourceList = testList; //调用公共属性 currentControl.setValue(); //调用公共方法 if (currentControl is ddl) { currentControl.RenderControl(writer); Response.Write( sw.ToString()); } } }

       方案二:采用一个公共类A去继承 System.Web.UI.UserControl,然后再在其中添加接口。然后usercontrol去继承这个公共类A然后

                  再去实现类A中的接口。

                 公共类 BaseQueryControl

        public abstract class BaseQueryControl:UserControl  //注意这里要继承UserControl
        {
            public abstract void SetDataSourceBind(object source); //这里是接口
        }

                用户控件

     public partial class EnumeratorControl : BaseQueryControl //继承公共类
        {public override void SetDataSourceBind(object source) //重载方法
            {
                if (source!=null)
                {
                    this.ddl.DataSource = source;
                    this.ddl.DataBind();                
                }
            }
    }

                  这样做有一个好处,就是可以统一管理继承了类A的所以usercontrol。

  • 相关阅读:
    开发Django项目01
    本地安装python2.x和python3.x双版本之后怎么使用pip
    python3.x并发编程
    centos6.8安装JDK1.8教程
    yum安装MySQL指定版本
    python爬虫爬取get请求的页面数据代码样例
    python网络爬虫学习笔记
    python通过get方式,post方式发送http请求和接收http响应-urllib urllib2
    CentOS7.5安装python-pip报Error: Nothing to do解决方法
    文件操作
  • 原文地址:https://www.cnblogs.com/msql/p/2848100.html
Copyright © 2011-2022 走看看