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.可以在类外部确定加载的是哪个用户自定义控件

  • 相关阅读:
    变量的创建和初始化
    HDU 1114 Piggy-Bank (dp)
    HDU 1421 搬寝室 (dp)
    HDU 2059 龟兔赛跑 (dp)
    HDU 2571 命运 (dp)
    HDU 1574 RP问题 (dp)
    HDU 2577 How to Type (字符串处理)
    HDU 1422 重温世界杯 (dp)
    HDU 2191 珍惜现在,感恩生活 (dp)
    HH实习 acm算法部 1689
  • 原文地址:https://www.cnblogs.com/wxzl/p/2324628.html
Copyright © 2011-2022 走看看