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。

  • 相关阅读:
    实践:VIM深入研究(20135301 && 20135337)
    信息安全系统设计基础第十二周学习总结
    信息安全系统设计基础第五次实验报告 20135201&&20135306&&20135307
    信息安全系统设计基础第四次实验报告 20135201&&20135306&&20135307
    信息安全系统设计基础第三次实验报告 20135201&&20135306&&20135307
    信息安全系统设计基础第二次实验报告 20135201&&20135306&&20135307
    深入理解计算机系统家庭作业汇总 20135301&&20135328
    java 基本理论知识点
    使用DAO模式开发宠物管理系统
    java编程常用的快捷键
  • 原文地址:https://www.cnblogs.com/msql/p/2848100.html
Copyright © 2011-2022 走看看