Asp.net custom controls: Single-choice and multi-choice controls; asp.net multi-Choice

Source: Internet
Author: User

Asp.net custom controls: Single-choice and multi-choice controls; asp.net multi-Choice

The example in this article shares the specific implementation code of the Asp.net single choice and check box controls for your reference. The specific content is as follows:

Encapsulating commonly used jquery plug-ins into controls is also a good choice.

First look at the effect:

1. Create a class library project and a data source class

 [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. Create a control CheckList class, inherit from WebControl, and define the attribute of the public List <Select2Item> Items data item.

3. Introduce script files and style files 
A. Create a script or style file, set file properties-generate operations-embedded Resources

B. Add the mark [assembly: WebResource ("namespace. Folder name. File Name", "mime type")] on the namespace.
For example:
[Assembly: WebResource ("Control.Style.checklist.css", "text/css", required msubstitution = true)]
[Assembly: WebResource ("Control. Scripts. checklist. js", "application/x-javascript")]

If an image exists in the css file, set the image as an embedded resource and write it in css as <% = WebResource ("namespace. Folder name. File Name") %>
 PerformSubstitution indicates whether to analyze other Web Resource URLs during the processing of embedded resources and replace them with the complete path of the resource.
C. Rewrite protected override void OnPreRender (EventArgs e) to introduce embedded scripts or style files.
If (Page! = Null) Page. header. controls. add (LiteralControl), put the <script> <link> label in LiteralControl, and Add LiteralControl to Page. header, and then you will see the introduced <script> <link> label in the page.

 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. override the protected override void Render (HtmlTextWriter writer) method of the control.
Here is the html of the Rendering Control, depending on your control.

 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>");  } } 

5. Add the GetSelected method, return List <Select2Item>, add GetSelectValue, and return String (multiple values are separated by commas)

 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. Save status
You need to override two methods: protected override object SaveViewState () and protected override void LoadViewState (object savedState) to save the attributes of the Items data item to 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]; } 

7. Single-choice and check settings are controlled in js
Add attribute
[Description ("obtain and set multiple options"), DefaultValue (true), Browsable (true), Category ("Miscellaneous")]
Public bool Multiple {get; set ;}
In the OnPreRender code, you will find that the Multiple attribute affects the mul attribute value of the div to determine whether to select Multiple values (Multiple values are selected by default)
 8. Other Instructions
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 ";

:

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.