zoukankan      html  css  js  c++  java
  • 用户控件生成代码

      看了这篇博文 http://blog.zhaojie.me/2007/12/usercontrol-as-an-template.html

     做了个练习

    用户自定义控件生成代码

    1.我们需要一个一般处理程序 (ashx页面)

      在这个页面中我们创建一个control 并为属性字段赋值

    2.将之前创建的contral 放到一个page对象的contrals集合中

    3.将页面请求转交给上面说过的page对象 主要是利用了

       HttpContext.Current.Server.Execute方法

    下面附上代码

    (ashx)

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;

    namespace WebForm
    {

    public class UtTest : IHttpHandler
    {

    public void ProcessRequest(HttpContext context)
    {
    context.Response.ContentType = "text/plain";
    UserControl<UT> userControl = new UserControl<UT>();
    userControl.LoadUserControl("UT.ascx");
    context.Response.Write(userControl.RenderView());
    }

    public bool IsReusable
    {
    get
    {
    return false;
    }
    }
    }
    }

    测试用的ascx

    <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="UT.ascx.cs" Inherits="WebForm.UT" %>
    <asp:Repeater ID="wx" runat="server">
    <ItemTemplate>
    wangxiao
    </ItemTemplate>
    </asp:Repeater>
    .cs 文件
    ...
    ...
    ...

    namespace WebForm
    {
    public partial class UT : System.Web.UI.UserControl
    {
    protected string zl = "zhanglin";
    protected void Page_Load(object sender, EventArgs e)
    {
    wx.DataSource = new int[] { 1,3,5};
    wx.DataBind();
    }
    }
    }

    最重要的包含page对象的类

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.IO;

    namespace WebForm
    {
    public class UserControl<T> where T : UserControl
    {
    protected Page page = new Page();
    public T LoadUserControl(string userControlPath)
    {
    Control contral = page.LoadControl(userControlPath);
    page.Controls.Add(contral);
    return (T)contral;
    }

    public string RenderView()
    {
    StringWriter sw = new StringWriter();
    HttpContext.Current.Server.Execute(page, sw, false);
    return sw.ToString();
    }
    }
    }

    下面谈谈 我对 最后这个类的看法

     原来是想吧类定义成 静态的的 结果发现 会有问题 原因也很简单,

    这样做的有几点好处 

    1.在创建对象的时候确定了具体的类型

    2.可以在类外部确定加载的是哪个用户自定义控件

  • 相关阅读:
    读书笔记之理想设计的特征
    一些javascript 变量声明的 疑惑
    LINQ 使用方法
    Google MySQL tool releases
    读书笔记之设计的层次
    EF之数据库连接问题The specified named connection is either not found in the configuration, not intended to be used with the Ent
    转载 什么是闭包
    javascript面向对象起步
    Tips
    数据结构在游戏中的应用
  • 原文地址:https://www.cnblogs.com/wxzl/p/2324628.html
Copyright © 2011-2022 走看看