重写RadioButtonList服务器控件的RenderItem方法,隐藏radio元素

来源:互联网 发布:网络棋牌刷分赚钱 编辑:程序博客网 时间:2024/06/13 04:37

思路:先判断浏览器是否为IE浏览器,如果是IE浏览器就将radio元素样式为width:0px;height:0px;若不是IE浏览器就将radio元素的样式设置为display:none。

//注释掉原来的RenderItem方法//base.RenderItem(itemType, repeatIndex, repeatInfo, writer);bool isIE = HttpContext.Current.Request.UserAgent.ToLower().IndexOf("msie") > 0;ListItem li = Items[repeatIndex];//回调函数的eventTargetstring name = this.ClientID.Replace('_','$')+"$"+repeatIndex.ToString();//用于radio元素的name属性string pname = this.ClientID.Replace('_','$');//用于radio元素的id属性及label标签的for属性string id = this.ClientID + "_" + repeatIndex.ToString();//定义当AutoPostBack=true时的回调string onclick = AutoPostBack?"onclick=\"javascript:setTimeout(\'__doPostBack(\\'"+name+"\\',\\'"+li.Value+"\\')\',0)\"":"";//SelectedCssClass和ItemCssClass是我增加的两个Css,分别用于选中项的label和未选中项的label标签的class。string css = li.Selected ? SelectedCssClass : ItemCssClass;//可以在标签外围增加新标签,如<div style=''>{0}{1}</div>string div = "{0}{1}";//若为IE浏览器style=width:0px;height:0px; 其他浏览器style=display:none;string radio = "<input type='radio' id='"+id+"' name='"+pname+"' value='"+li.Value+"'"+onclick+" style='"+(isIE?"width:0px;height:0px;":"display:none;")+"'/>";string label = "<label for='"+id+"' class='"+css+"'>"+li.Text+"</label>";writer.Write(string.Format(div,radio,label));

实测FF/IE浏览器效果相同

radio元素被隐藏,图中的按钮均为带css的label标签,当设置AutoPostBack=true时的回调也正常