码迷,mamicode.com
首页 > Web开发 > 详细

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

时间:2016-01-06 17:25:18      阅读:297      评论:0      收藏:0      [点我收藏+]

标签:

将常用的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.创建脚本或样式文件,设置文件的属性-生成操作-嵌入的资源

 技术分享

 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);
        }
View Code

 

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

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

技术分享
        protected override void Render(HtmlTextWriter writer)
        {
            if (Items.Count > 0)
            {
                writer.Write("<div id=‘div" + this.ClientID + "‘ class=‘c01-tag-div‘ mul=‘" + (Multiple == true ? "1" : "0") + "‘>");
                if (Multiple == false)
                    writer.Write("<input name=‘tb" + this.ClientID + "‘ type=‘hidden‘ value=‘" + Items[0].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>");
            }
        }
View Code

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;
            }
        }
View Code
技术分享
        public string GetSelectValue()
        {
            if (Page != null)
            {
                return Page.Request.Form["tb" + this.ClientID];
            }
            return "";
        }
View Code

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[0] != null)
                base.LoadViewState(vState[0]);
            if (vState[1] != null)
                Items = (List<Select2Item>)vState[1];
        }
View Code

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自定义单选复选框控件

标签:

原文地址:http://www.cnblogs.com/liuxiaobo93/p/5103472.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!