Asp.net自定义单选复选框控件

时间:2023-01-06 21:45:45

将常用的jquery插件封装成控件也是个不错的选择

下面是效果的简单颜色,由于博客系统的限制没法完整演示最终效果,请下载示例查看

 

1.新建类库项目,创建数据源类

    [Serializable]
public class Select2Item
{
public bool Selected { get; set; } public string Text { get; set; } public string Value { get; set; } public Select2Item() { } public Select2Item(string text, string value)
{
this.Text = text;
this.Value = value;
} public Select2Item(string text, string value, bool selected)
{
this.Text = text;
this.Value = value;
this.Selected = selected;
}
}

2.创建控件类CheckList,继承与WebControl,并定义 public List<Select2Item> Items数据项属性。

3.引入脚本文件及样式文件

a.创建脚本或样式文件,设置文件的属性-生成操作-嵌入的资源

Asp.net自定义单选复选框控件

b.需要在namespace上添加标记 [assembly: WebResource("命名空间.文件夹名.文件名", "mime类型")]

如:

[assembly: WebResource("Control.Style.checklist.css", "text/css",PerformSubstitution = true)]
    [assembly: WebResource("Control.Scripts.checklist.js", "application/x-javascript")]

如果css文件里面存在图片的话,同样将图片设置为嵌入的资源,在css中的写法为<%=WebResource("命名空间.文件夹名.文件名")%>

PerformSubstitution 表示嵌入式资源的处理过程中是否分析其他Web 资源 URL,并用到该资源的完整路径替换。

c.重写protected override void OnPreRender(EventArgs e),引入嵌入的脚本或样式文件

if(Page!=null) Page.Header.Controls.Add(LiteralControl),将<script><link>标签放到LiteralControl中,然后将LiteralControl添加到Page.Header中,最后在页面里你就会看到引入的<script><link>标签。

        protected override void OnPreRender(EventArgs e)
{
if (this.Page != null)
{
StringBuilder sbb = new StringBuilder();
sbb.Append(string.Format(STYLE_TEMPLATE, Page.ClientScript.GetWebResourceUrl(this.GetType(), "HandControl.Style.checklist.css")));
sbb.Append(string.Format(SCRIPT_TEMPLATE, Page.ClientScript.GetWebResourceUrl(this.GetType(), "HandControl.Scripts.checklist.js"))); bool hascss = false;
LiteralControl lcc = new LiteralControl(sbb.ToString());
lcc.ID = "lccheck";
foreach (Control item in Page.Header.Controls)
{
if (item.ID == "lccheck")
hascss = true;
}
if (!hascss)
Page.Header.Controls.Add(lcc);
}
base.OnPreRender(e);
}

4.重写控件的protected override void Render(HtmlTextWriter writer)方法

这里主要是渲染控件的html,根据你的控件而定。

        protected override void Render(HtmlTextWriter writer)
{
if (Items.Count > )
{
writer.Write("<div id='div" + this.ClientID + "' class='c01-tag-div' mul='" + (Multiple == true ? "" : "") + "'>");
if (Multiple == false)
writer.Write("<input name='tb" + this.ClientID + "' type='hidden' value='" + Items[].Value + "' />");
else
writer.Write("<input name='tb" + this.ClientID + "' type='hidden' />");
bool first = true;
foreach (var item in Items)
{
if (Multiple == false)
{
if (item.Selected && first)
{
writer.Write("<a title='" + item.Text + "' class='c01-tag-item c01-tag-select' val='" + item.Value + "' tag='Y'>" + item.Text + "</a>");
first = false;
}
else
{
writer.Write("<a title='" + item.Text + "' class='c01-tag-item' val='" + item.Value + "' tag='N'>" + item.Text + "</a>");
}
}
else
{
if (item.Selected)
writer.Write("<a title='" + item.Text + "' class='c01-tag-item c01-tag-select' val='" + item.Value + "' tag='Y'>" + item.Text + "</a>");
else
writer.Write("<a title='" + item.Text + "' class='c01-tag-item' val='" + item.Value + "' tag='N'>" + item.Text + "</a>");
}
}
writer.Write("</div>");
}
}

5.添加GetSelected方法,返回List<Select2Item>,添加GetSelectValue,返回String(多选以,号隔开)

        public List<Select2Item> GetSelected()
{
if (Page != null)
{
var values = Page.Request.Form["tb" + this.ClientID].Split(',');
var res = Items.Where(t => values.Contains(t.Value)).ToList();
foreach (var item in Items)
{
if (res.Contains(item))
{
item.Selected = true;
}
else
{
item.Selected = false;
}
}
return res;
}
else
{
return null;
}
}
        public string GetSelectValue()
{
if (Page != null)
{
return Page.Request.Form["tb" + this.ClientID];
}
return "";
}

6.保存状态

你需要重写两个方法protected override object SaveViewState() 、protected override void LoadViewState(object savedState),旨在将Items数据项属性保存到ViewState

        protected override object SaveViewState()
{
var valuestr = Page.Request.Form["tb" + this.ClientID];
if (!string.IsNullOrEmpty(valuestr))
{
var values = valuestr.Split(',');
var temp = Items.Where(t => values.Contains(t.Value)).ToList();
foreach (var item in temp)
{
item.Selected = true;
}
}
return new object[] { base.SaveViewState(), Items };
} protected override void LoadViewState(object savedState)
{
object[] vState = (object[])savedState;
if (vState[] != null)
base.LoadViewState(vState[]);
if (vState[] != null)
Items = (List<Select2Item>)vState[];
}

7.单选和复选的设置,在js中控制

添加属性

[Description("获取和设置多选"), DefaultValue(true), Browsable(true), Category("杂项")]
public bool Multiple { get; set; }

在OnPreRender代码中你会发现Multiple属性会影响div的mul属性值,从而判断是否多选(默认多选)

8.其它说明

private static readonly string STYLE_TEMPLATE = "<link href=\"{0}\" rel=\"stylesheet\" type=\"text/css\" />\r\n";
private static readonly string SCRIPT_TEMPLATE = "<script type=\"text/javascript\" src=\"{0}\"></script>\r\n";

效果图:

Asp.net自定义单选复选框控件Asp.net自定义单选复选框控件