zoukankan      html  css  js  c++  java
  • asp.net服务器控件开发系列一

    最近想写写博客记录下自己学习开发服务器控件。

    第一步:搭建环境。

    1、新建一个项目类库,用于保存控件;

    2、新建一个Web工程,用于调用控件;

    如图:

    第二步:在控件类库下,新建一个服务器控件类TextBox.cs文件。代码如下:

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Linq;
    using System.Text;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    
    namespace JHSoft.UI.Web.Controls
    {
        [DefaultProperty("Text")]
        [ToolboxData("<{0}:TextBox runat=server></{0}:TextBox>")]
        public class TextBox : WebControl
        {
            [Bindable(true)]
            [Category("Appearance")]
            [DefaultValue("")]
            [Localizable(true)]
            public string Text
            {
                get
                {
                    String s = (String)ViewState["Text"];
                    return ((s == null) ? String.Empty : s);
                }
    
                set
                {
                    ViewState["Text"] = value;
                }
            }
    
            protected override void RenderContents(HtmlTextWriter output)
            {
                output.Write(Text);
            }
        }
    }

    修改方法:RenderContents

      protected override void RenderContents(HtmlTextWriter output)
            {
                output.Write("<input type='text' value='" + Text + "'/>");
            }

    第三步:

    1、引用控件类库。

    2、在Webconfig中注册控件前缀

    3、在Web工程中,新建一个页面TextBox.aspx,调用新建的服务器控件<c:TextBox>

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="TextBox.aspx.cs" Inherits="JHSoft.SYS.Web.TextBox" %>
    
    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title></title>
    </head>
    <body>
        <form id="form1" runat="server">
    
            <c:TextBox runat="server" Text="Test"></c:TextBox>
    
        </form>
    </body>
    </html>

    需要说明的是:

    此处的控件 <c:TextBox runat="server" Text="Test"></c:TextBox>,执行完成后,生成的html代码是:

    TextBox.cs类中的

    protected override void RenderContents(HtmlTextWriter output)
    {
    output.Write("<input type='text' value='" + Text + "'/>");   //生成的普通控件,Text为显示的值
    }

    源码下载

  • 相关阅读:
    附加作业
    我的个人总结
    进度更新
    结对编程——电梯调度
    程序阅读的改进
    WordCount
    阅读程序
    VS2013单元测试
    附加作业
    个人最终总结
  • 原文地址:https://www.cnblogs.com/renzaijianghu/p/4098350.html
Copyright © 2011-2022 走看看