Asp.net自定義單選復選框控件


將常用的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";

效果圖:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM