汉广

常怀恭敬之心
随笔 - 16, 文章 - 0, 评论 - 134, 引用 - 2
数据加载中……

使用Control Adapters优化Asp.net控件

 

 

有些时候Asp.net 控件默认状态下生成的html代码,不能满足一些特定的需要。比如

我们想让用户做一些选择,可以很容易的用如下代码实现

<asp:CheckBoxList runat="server">

   <asp:ListItem Text="One" />

   <asp:ListItem Text="Two" />

   <asp:ListItem Text="Three" />

</asp:CheckBoxList>


默认状态下CheckBoxList会将这些选项放在一个table标签里,但是也许有个别情况不适合使用table,而需要一个un-ordered list(ul)。当然我们可以重新写一个继承于CheckBoxList的控件,但是使用Control Adpater会更容易,并且还有一些额外的好处。

首先看一下实现:

1 写一个继承自WebControlAdapter的类,如下

using System;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.Adapters;

public class RadioButtonListAdapter : WebControlAdapter

{

   protected override void Render(HtmlTextWriter writer)

   {

       ListControl targetControl = this.Control as ListControl;

       // If the control that this adapter is pointing to is not

       // a ListControl (RadioButtonList or CheckBoxList) then

       // we don't want to change the rendering.

       if (targetControl == null || targetControl is IRepeatInfoUser == false)

       {

         

 

base.Render(writer);

           return;

       }

       writer.WriteBeginTag("ul");

       if (targetControl.CssClass.Length > 0)

       {

 

         writer.WriteAttribute("class", targetControl.CssClass);

       }

       writer.Write(">");

       IRepeatInfoUser repeaterInfo = (IRepeatInfoUser)this.Control;

       for (int i = 0; i < targetControl.Items.Count; i++)

       {

           writer.WriteFullBeginTag("li");

           repeaterInfo.RenderItem(ListItemType.Item, i, new RepeatInfo(), writer);

           writer.WriteEndTag("li");

       }

       writer.WriteEndTag("ul");

   }

}


2,新建一个asp.net 文件夹 App_Browsers,在其中添加一个.browser文件,添加如下内容

<browsers>

<browser refID="Default">

       <controlAdapters>

           <adapter controlType="System.Web.UI.WebControls.CheckBoxList"

              adapterType="RadioButtonListAdapter" />

           <adapter controlType="System.Web.UI.WebControls.RadioButtonList"

              adapterType="RadioButtonListAdapter" />

       </controlAdapters>

   </browser>

</browsers>


好了,一切ok。注意到了没有?我们并没有改变先前的asp.net代码.这就是个非常重要的好处啊。

 

Ps : Most of information and code of this article come from Timothy Khouri's

Cool website SingingEels 

 

 

 

 

 

 

 

posted on 2007-06-01 10:15 汉广 阅读(268) 评论(4)  编辑 收藏 所属分类: Asp.net

评论

#1楼    回复  引用    

不错!
2007-06-22 17:33 | chen [未注册用户]

#2楼    回复  引用  查看    

http://www.xq168.cn引用了你的文章
2008-02-22 13:36 | HeroBeast      

#3楼 [楼主]   回复  引用  查看    

@HeroBeast
欢迎
2008-02-22 14:11 | 汉广      

#4楼 [楼主]   回复  引用  查看    

-------------------------
汉广同学正在找工作,你可以点击这里 ,浏览他的简历:-)
2008-02-26 15:53 | 汉广      

标题  
姓名  
主页
Email (只有博主才能看到) 
验证码 *  看不清,换一张 [登录][注册]
内容(请不要发表任何与政治相关的内容)  
  登录  使用高级评论  新用户注册  返回页首  恢复上次提交      
该文被作者在 2008-01-31 16:41 编辑过


相关链接: