ASP. net mvc adds a RadioButtonList Extension Method for HtmlHelper

Source: Internet
Author: User

In the previous http://www.bkjia.com/kf/201203/123222.html article, we simplified the binding to DropDownList (Single-Line-Select) and ListBox (Multiple-Line-Select) by extending HtmlHelper, and separately maintain the list of data sources. Now we add a RadioButtonList/RadioButtonListFor Extension Method for HtmlHelper/HtmlHelper <Model> to bind a group of RadioButton instances. [Source code http://www.bkjia.com/uploadfile/2012/0316/20120316090259232.rar here
Download]
1. Use of RadioButtonListFor
Let's first display the usage of the extended RadioButtonListFor method. The following shows the Person type of the Model. Its Gender (Male/Female), MaritalStatus (Single/Married), and Country options are maintained separately through the Independent Component CodeManager.
1: public class Person
2 :{
3: public string Name {get; set ;}
4: public string Gender {get; set ;}
5: [Display (Name = "marw.status")]
6: public string MaritalStatus {get; set ;}
7: public string Country {get; set ;}
8 :}
In a strong View (with Person as the Model) That is edited for the Person object, we define the following. The last parameter ("Gender", "MaritalStatus", and "Country") of RadioButtonListFor indicates the category of the corresponding list.
1: @ using System. Web. UI. WebControls
2: @ model Person
3 :@{
4: ViewBag. Title = "Index ";
5 :}
6: @ using (Html. BeginForm ())
7 :{
8: <table id = "container">
9: <tr>
10: <td class = "label"> @ Html. LabelFor (m => m. Name): </td>
11: <td> @ Html. EditorFor (m => m. Name) </td>
12: </tr>
13: <tr>
14: <td class = "label"> @ Html. LabelFor (m => m. Gender): </td>
15: <td> @ Html. RadioButtonListFor (m => m. Gender, "Gender") </td>
16: </tr>
17: <tr>
18: <td class = "label"> @ Html. LabelFor (m => m. MaritalStatus): </td>
19: <td> @ Html. RadioButtonListFor (m => m. MaritalStatus, "MaritalStatus") </td>
20: </tr>
21: <tr>
22: <td class = "label"> @ Html. LabelFor (m => m. Country): </td>
23: <td> @ Html. RadioButtonListFor (m => m. Country, "Country", RepeatDirection. Vertical) </td>
24: </tr>
25: <tr>
26: <td colspan = "2"> <input type = "submit" value = "Save"/> </td>
27: </tr>
28: </table>
29 :}
The following figure shows the style displayed in the browser. We can see that three groups of RadioButton are effectively generated.


Ii. Maintain the CodeManager component of the Option List
In an application, there may be many option lists bound to the "list control", so it is ideal to maintain them separately. As a simulation, we have created a simple CodeManager component, for example. We use CodeDescription for an option in the list. The three attributes Code and Description indicate their "value" and "display text" respectively, and Category indicate the Category (through which list items are grouped ). CodeManager stores the List data using a static field. The three groups of lists used in the preceding example are maintained here. The GetCodes method is used to return the list options of the specified "category.
1: public class CodeDescription
2 :{
3: public string Code {get; set ;}
4: public string Description {get; set ;}
5: public string Category {get; set ;}
6:
7: public CodeDescription (string code, string description, string category)
8 :{
9: this. Code = code;
10: this. Description = description;
11: this. Category = category;
12 :}
13 :}
14: public static class CodeManager
15 :{
16: private static CodeDescription [] codes = new CodeDescription []
17 :{
18: new CodeDescription ("M", "Male", "Gender "),
19: new CodeDescription ("F", "Female", "Gender "),
20: new CodeDescription ("S", "Single", "MaritalStatus "),
21: new CodeDescription ("M", "Married", "MaritalStatus "),
22: new CodeDescription ("CN", "China", "Country "),
23: new CodeDescription ("US", "Unite States", "Country "),
24: new CodeDescription ("UK", "Britain", "Country "),
25: new CodeDescription ("SG", "Singapore", "Country ")
26 :};
27: public static Collection <CodeDescription> GetCodes (string category)
28 :{
29: Collection <CodeDescription> codeCollection = new Collection <CodeDescription> ();
30: foreach (var code in codes. Where (code => code. Category = category ))
31 :{
32: codeCollection. Add (code );
33 :}
34: return codeCollection;
35 :}
36 :}

3. RadioButtonList/RadioButtonListFor Extension Method
The following is the definition of the two extension methods of RadioButtonList/RadioButtonListFor. The codeCategory parameter represents the list category of the data source, and the RepeatDirection Enumeration type represents the direction of the RadioButton group. The default value is horizontal. From the above example, we can see that we use this parameter to vertically arrange the RadioButtonList named Country. We can see from the Html generation code that we use Table as the layout method. In fact, the RadioButtonList of ASP. NET does the same.
1: public static class RadioButtonListExtensions
2 :{
3: public static MvcHtmlString RadioButtonList (this HtmlHelper htmlHelper, string name, string codeCategory, RepeatDirection repeatDirection = RepeatDirection. Horizontal, IDictionary <string, object> htmlAttributes = null)
4 :{
5: var codes = CodeManager. GetCodes (codeCategory );
6: return GenerateHtml (name, codes, repeatDirection, htmlAttributes, null );
7 :}
8: public static MvcHtmlString syntax <TModel, TProperty> (this HtmlHelper <TModel> htmlHelper, Expression <Func <TModel, TProperty> expression, string codeCategory, RepeatDirection repeatDirection = RepeatDirection. horizontal, IDictionary <string, object> htmlAttributes = null)
9 :{
10: var codes = CodeManager. GetCodes (codeCategory );
11:
12: ModelMetadata metadata = ModelMetadata. FromLambdaExpression <TModel, TProperty> (expression, htmlHelper. ViewData );
13: string name = ExpressionHelper. GetExpressionText (expression );
14: var attributes = htmlHelper. GetUnobtrusiveValidationAttributes (name, metadata );
15: foreach (var item in attributes)
16 :{
17: htmlAttributes. Add (item );
18 :}
19: string fullHtmlFieldName = htmlHelper. ViewContext. ViewData. TemplateInfo. GetFullHtmlFieldName (name );
20: string stateValue = (string) metadata. Model;
21: return GenerateHtml (fullHtmlFieldName, codes, repeatDirection, htmlAttributes, stateValue );
22 :}
23: private static MvcHtmlString GenerateHtml (string name, Collection <CodeDescription> codes, RepeatDirection repeatDirection, IDictionary <string, object> htmlAttributes, string stateValue = null)
24 :{
25: TagBuilder table = new TagBuilder ("table ");
26: int I = 0;
27: if (repeatDirection = RepeatDirection. Horizontal)
28 :{
29: TagBuilder tr = new TagBuilder ("tr ");
30: foreach (var code in codes)
31 :{
32: I ++;
33: string id = string. Format ("{0 }_{ 1}", name, I );
34: TagBuilder td = new TagBuilder ("td ");
35: td. InnerHtml = GenerateRadioHtml (name, id, code. Description, code. Code, (stateValue! = Null & stateValue = code. Code), htmlAttributes );
36: tr. InnerHtml + = td. ToString ();
37 :}
38: table. InnerHtml = tr. ToString ();
39 :}
40: else
41 :{
42: foreach (var code in codes)
43 :{
44: TagBuilder tr = new TagBuilder ("tr ");
45: I ++;
46: string id = string. Format ("{0 }_{ 1}", name, I );
47: TagBuilder td = new TagBuilder ("td ");
48: td. InnerHtml = GenerateRadioHtml (name, id, code. Description, code. Code, (stateValue! = Null & stateValue = code. Code), htmlAttributes );
49: tr. InnerHtml = td. ToString ();
50: table. InnerHtml + = tr. ToString ();
51 :}
52 :}
53: return new MvcHtmlString (table. ToString ());
54 :}
55:
56: private static string GenerateRadioHtml (string name, string id, string labelText, string value, bool isChecked, IDictionary <string, object> htmlAttributes)
57 :{
58: StringBuilder sb = new StringBuilder ();
59:
60: TagBuilder label = new TagBuilder ("label ");
61: label. MergeAttribute ("for", id );
62: label. SetInnerText (labelText );
63:
64: TagBuilder input = new TagBuilder ("input ");
65: input. GenerateId (id );
66: input. MergeAttribute ("name", name );
67: input. MergeAttribute ("type", "radio ");
68: input. MergeAttribute ("value", value );
69: input. MergeAttributes (htmlAttributes );
70: if (isChecked)
71 :{
72: input. MergeAttribute ("checked", "checked ");
73 :}
74: sb. AppendLine (input. ToString ());
75: sb. AppendLine (label. ToString ());
76: return sb. ToString ();
77 :}
78 :}

 

From Artech
 

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.