博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
The main reborn ASP.NET MVC4.0: using CheckBoxListHelper and RadioBoxListHelper
阅读量:6272 次
发布时间:2019-06-22

本文共 20945 字,大约阅读时间需要 69 分钟。

The new Helpers folder in the project, to create the CheckBoxListHelper and RadioBoxListHelper classes.

CheckBoxListHelper code

using System;using System.Collections.Generic;using System.Linq;using System.Linq.Expressions;using System.Text;using System.Web;using System.Web.Mvc;namespace SHH.Helpers{    public static class CheckBoxListHelper    {        public static MvcHtmlString CheckBoxList(this HtmlHelper helper, string name, bool isHorizon = true)        {            return CheckBoxList(helper, name, helper.ViewData[name] as IEnumerable
, new { }, isHorizon); } public static MvcHtmlString CheckBoxList(this HtmlHelper helper, string name, IEnumerable
selectList, bool isHorizon = true) { return CheckBoxList(helper, name, selectList, new { }, isHorizon); } public static MvcHtmlString CheckBoxListFor
(this HtmlHelper helper, Expression
> expression, IEnumerable
selectList, bool isHorizon = true) { string[] propertys = expression.ToString().Split(".".ToCharArray()); string id = string.Join("_", propertys, 1, propertys.Length - 1); string name = string.Join(".", propertys, 1, propertys.Length - 1); return CheckBoxList(helper, id, name, selectList, new { }, isHorizon); } public static MvcHtmlString CheckBoxList(this HtmlHelper helper, string name, IEnumerable
selectList, object htmlAttributes, bool isHorizon = true) { return CheckBoxList(helper, name, name, selectList, htmlAttributes, isHorizon); } public static MvcHtmlString CheckBoxList(this HtmlHelper helper, string id, string name, IEnumerable
selectList, object htmlAttributes, bool isHorizon = true) { IDictionary
HtmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes); HashSet
set = new HashSet
(); List
list = new List
(); string selectedValues = (selectList as SelectList).SelectedValue == null ? string.Empty : Convert.ToString((selectList as SelectList).SelectedValue); if (!string.IsNullOrEmpty(selectedValues)) { if (selectedValues.Contains(",")) { string[] tempStr = selectedValues.Split(','); for (int i = 0; i
newHtmlAttributes = HtmlAttributes.DeepCopy(); newHtmlAttributes.Add("value", selectItem.Value); if (selectItem.Selected) { newHtmlAttributes.Add("checked", "checked"); } TagBuilder tagBuilder = new TagBuilder("input"); tagBuilder.MergeAttributes
(newHtmlAttributes); string inputAllHtml = tagBuilder.ToString(TagRenderMode.SelfClosing); string containerFormat = isHorizon ? @"
" : @"

"; stringBuilder.AppendFormat(containerFormat, inputAllHtml, selectItem.Text); } return MvcHtmlString.Create(stringBuilder.ToString()); } private static IDictionary
DeepCopy(this IDictionary
ht) { Dictionary
_ht = new Dictionary
(); foreach (var p in ht) { _ht.Add(p.Key, p.Value); } return _ht; } }}

RadioBoxListHelper code

 

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Web;using System.Web.Mvc;namespace SHH.Helpers{    public static class RadioBoxListHelper    {        public static MvcHtmlString RadioBoxList(this HtmlHelper helper, string name)        {            return RadioBoxList(helper, name, helper.ViewData[name] as IEnumerable
, new { }); } public static MvcHtmlString RadioBoxList(this HtmlHelper helper, string name, IEnumerable
selectList) { return RadioBoxList(helper, name, selectList, new { }); } public static MvcHtmlString RadioBoxList(this HtmlHelper helper, string name, IEnumerable
selectList, object htmlAttributes) { IDictionary
HtmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes); HtmlAttributes.Add("type", "radio"); HtmlAttributes.Add("name", name); StringBuilder stringBuilder = new StringBuilder(); int i = 0; int j = 0; foreach (SelectListItem selectItem in selectList) { string id = string.Format("{0}{1}", name, j++); IDictionary
newHtmlAttributes = HtmlAttributes.DeepCopy(); newHtmlAttributes.Add("value", selectItem.Value); newHtmlAttributes.Add("id", id); var selectedValue = (selectList as SelectList).SelectedValue; if (selectedValue == null) { if (i++ == 0) newHtmlAttributes.Add("checked", null); } else if (selectItem.Value == selectedValue.ToString()) { newHtmlAttributes.Add("checked", null); } TagBuilder tagBuilder = new TagBuilder("input"); tagBuilder.MergeAttributes
(newHtmlAttributes); string inputAllHtml = tagBuilder.ToString(TagRenderMode.SelfClosing); stringBuilder.AppendFormat(@" {0}
", inputAllHtml, selectItem.Text, id); } return MvcHtmlString.Create(stringBuilder.ToString()); } private static IDictionary
DeepCopy(this IDictionary
ht) { Dictionary
_ht = new Dictionary
(); foreach (var p in ht) { _ht.Add(p.Key, p.Value); } return _ht; } }}

 

Enumeration to help the class code

using System;using System.Collections.Generic;using System.Linq;using System.Web;namespace SHH.Helpers{    ///     /// Enumeration helper classes    ///     public class EnumHelper    {        ///         /// Such as: "enum1, enum2 conversion, enum3" string to the enumeration values        ///         /// 
Enumeration types
/// The enumerated string ///
public static T Parse
(string obj) { if (string.IsNullOrEmpty(obj)) return default(T); else return (T)Enum.Parse(typeof(T), obj); } public static T TryParse
(string obj, T defT = default(T)) { try { return Parse
(obj); } catch { return defT; } } public static readonly string ENUM_TITLE_SEPARATOR = ","; ///
/// According to the enumeration value, return a string describing the /// If multiple enumeration, return to the "," separated string /// ///
///
public static string GetEnumTitle(Enum e, Enum language = null) { if (e == null) { return ""; } string[] valueArray = e.ToString().Split(ENUM_TITLE_SEPARATOR.ToArray(), StringSplitOptions.RemoveEmptyEntries); Type type = e.GetType(); string ret = ""; foreach (string enumValue in valueArray) { System.Reflection.FieldInfo fi = type.GetField(enumValue.Trim()); if (fi == null) continue; EnumTitleAttribute[] attrs = fi.GetCustomAttributes(typeof(EnumTitleAttribute), false) as EnumTitleAttribute[]; if (attrs != null && attrs.Length > 0 && attrs[0].IsDisplay) { ret += attrs[0].Title + ENUM_TITLE_SEPARATOR; } } return ret.TrimEnd(ENUM_TITLE_SEPARATOR.ToArray()); } ///
/// According to the enumeration value, return a string describing the /// If multiple enumeration, return to the "," separated string /// ///
///
public static string GetAllEnumTitle(Enum e, Enum language = null) { if (e == null) { return ""; } string[] valueArray = e.ToString().Split(ENUM_TITLE_SEPARATOR.ToArray(), StringSplitOptions.RemoveEmptyEntries); Type type = e.GetType(); string ret = ""; foreach (string enumValue in valueArray) { System.Reflection.FieldInfo fi = type.GetField(enumValue.Trim()); if (fi == null) continue; EnumTitleAttribute[] attrs = fi.GetCustomAttributes(typeof(EnumTitleAttribute), false) as EnumTitleAttribute[]; if (attrs != null && attrs.Length > 0) { ret += attrs[0].Title + ENUM_TITLE_SEPARATOR; } } return ret.TrimEnd(ENUM_TITLE_SEPARATOR.ToArray()); } public static EnumTitleAttribute GetEnumTitleAttribute(Enum e, Enum language = null) { if (e == null) { return null; } string[] valueArray = e.ToString().Split(ENUM_TITLE_SEPARATOR.ToArray(), StringSplitOptions.RemoveEmptyEntries); Type type = e.GetType(); EnumTitleAttribute ret = null; foreach (string enumValue in valueArray) { System.Reflection.FieldInfo fi = type.GetField(enumValue.Trim()); if (fi == null) continue; EnumTitleAttribute[] attrs = fi.GetCustomAttributes(typeof(EnumTitleAttribute), false) as EnumTitleAttribute[]; if (attrs != null && attrs.Length > 0) { ret = attrs[0]; break; } } return ret; } public static string GetDayOfWeekTitle(DayOfWeek day, Enum language = null) { switch (day) { case DayOfWeek.Monday: return "Monday"; case DayOfWeek.Tuesday: return "Tuesday"; case DayOfWeek.Wednesday: return "Wednesday"; case DayOfWeek.Thursday: return "Thursday"; case DayOfWeek.Friday: return "Friday"; case DayOfWeek.Saturday: return "Saturday"; case DayOfWeek.Sunday: return "Sunday"; default: return ""; } } ///
/// Returns the key value pairs, built for the name of the specified enumeration of EnumTitle and synonym name, value is the enumeration entries /// ///
Enumeration types
///
///
public static Dictionary
GetTitleAndSynonyms
(Enum language = null) where T : struct { Dictionary
ret = new Dictionary
(); //Enumeration values Array arrEnumValue = typeof(T).GetEnumValues(); foreach (object enumValue in arrEnumValue) { System.Reflection.FieldInfo fi = typeof(T).GetField(enumValue.ToString()); if (fi == null) { continue; } EnumTitleAttribute[] arrEnumTitleAttr = fi.GetCustomAttributes(typeof(EnumTitleAttribute), false) as EnumTitleAttribute[]; if (arrEnumTitleAttr == null || arrEnumTitleAttr.Length <1 || !arrEnumTitleAttr[0].IsDisplay) { continue; } if (!ret.ContainsKey(arrEnumTitleAttr[0].Title)) { ret.Add(arrEnumTitleAttr[0].Title, (T)enumValue); } if (arrEnumTitleAttr[0].Synonyms == null || arrEnumTitleAttr[0].Synonyms.Length <1) { continue; } foreach (string s in arrEnumTitleAttr[0].Synonyms) { if (!ret.ContainsKey(s)) { ret.Add(s, (T)enumValue); } } }//using return ret; } ///
/// Based on the enumeration to obtain contains all all values and describe the hash table, the text is composed by the application in the enumeration values on the EnumTitleAttribute set /// ///
public static Dictionary
GetItemList
(Enum language = null) where T : struct { return GetItemValueList
(false, language); } ///
/// Based on the enumeration to obtain contains all all values and describe the hash table, the text is composed by the application in the enumeration values on the EnumTitleAttribute set /// ///
public static Dictionary
GetAllItemList
(Enum language = null) where T : struct { return GetItemValueList
(true, language); } ///
/// Access to enumerate all the title, the text is composed by the application in the enumeration values on the EnumTitleAttribute set /// ///
Enumeration types
///
Language ///
public static Dictionary
GetItemValueList
(Enum language = null) where T : struct { return GetItemValueList
(false, language); } ///
/// Access to enumerate all the title, the text is composed by the application in the enumeration values on the EnumTitleAttribute set /// ///
Enumeration types
///
Whether to build the "all" ///
Language ///
public static Dictionary
GetItemValueList
(bool isAll, Enum language = null) where T : struct { if (!typeof(T).IsEnum) { throw new Exception("The parameter must be enumerated!"); } Dictionary
ret = new Dictionary
(); var titles = EnumHelper.GetItemAttributeList
().OrderBy(t => t.Value.Order); foreach (var t in titles) { if (!isAll && (!t.Value.IsDisplay || t.Key.ToString() == "None")) continue; if (t.Key.ToString() == "None" && isAll) { ret.Add((TKey)(object)t.Key, "All"); } else { if (!string.IsNullOrEmpty(t.Value.Title)) ret.Add((TKey)(object)t.Key, t.Value.Title); } } return ret; } public static List
GetItemKeyList
(Enum language = null) where T : struct { List
list = new List
(); Array array = typeof(T).GetEnumValues(); foreach (object t in array) { list.Add((T)t); } return list; } public static Dictionary
GetItemAttributeList
(Enum language = null) where T : struct { if (!typeof(T).IsEnum) { throw new Exception("The parameter must be enumerated!"); } Dictionary
ret = new Dictionary
(); Array array = typeof(T).GetEnumValues(); foreach (object t in array) { EnumTitleAttribute att = GetEnumTitleAttribute(t as Enum, language); if (att != null) ret.Add((T)t, att); } return ret; } ///
/// Access to enumerate all the title, the text is composed by the application in the enumeration values on the EnumTitleAttribute set /// ///
Enumeration types
///
Whether to build the "all" ///
Language ///
public static Dictionary
GetAllItemValueList
(Enum language = null) where T : struct { return GetItemValueList
(true, language); } ///
/// Gets an enumeration pairs /// ///
Enumeration types
///
Exclude the enumeration ///
public static Dictionary
GetEnumDictionary
(IEnumerable
exceptTypes = null) where TEnum : struct { var dic = GetItemList
(); Dictionary
dicNew = new Dictionary
(); foreach (var d in dic) { if (exceptTypes != null && exceptTypes.Contains(d.Key)) { continue; } dicNew.Add(d.Key.GetHashCode(), d.Value); } return dicNew; } } public class EnumTitleAttribute : Attribute { private bool _IsDisplay = true; public EnumTitleAttribute(string title, params string[] synonyms) { Title = title; Synonyms = synonyms; Order = int.MaxValue; } public bool IsDisplay { get { return _IsDisplay; } set { _IsDisplay = value; } } public string Title { get; set; } public string Description { get; set; } public string Letter { get; set; } ///
/// Synonyms /// public string[] Synonyms { get; set; } public int Category { get; set; } public int Order { get; set; } }}

Enumeration data code

using System;using System.Collections.Generic;using System.Linq;using System.Web;namespace SHH.Helpers{    public class EnumData    {        ///         /// Gender        ///         public enum EnumSex        {            [EnumTitle("Hello, sir")]            Sir = 1,            [EnumTitle("Ma'am")]            Miss = 2        }        ///         /// Make an appointment        ///         public enum EnumBespeakDate        {            [EnumTitle("Working days (Monday to Friday)")]            BespeakDate1 = 1,            [EnumTitle("The weekend")]            BespeakDate2 = 2,            [EnumTitle("Weekdays or weekends")]            BespeakDate3 = 3        }        ///         /// Appointments        ///         public enum EnumBespeakTime        {            [EnumTitle("Morning")]            BespeakTime1 = 1,            [EnumTitle("The afternoon")]            BespeakTime2 = 2,            [EnumTitle("Night")]            BespeakDate3 = 3,            [EnumTitle("At any time")]            BespeakDate4= 4        }        ///         /// The price        ///         public enum EnumPriceGroup        {            [EnumTitle("Unlimited", IsDisplay = false)]            None = 0,            [EnumTitle("300000 the following")]            Below30 = 1,            [EnumTitle("30-50 million")]            From30To50 = 2,            [EnumTitle("50-80 million")]            From50To80 = 3,            [EnumTitle("80-100 million")]            From80To100 = 4,            [EnumTitle("100-150 million")]            From100To50 = 5,            [EnumTitle("150-200 million")]            From150To200 = 6,            [EnumTitle("More than 2000000")]            Above200 = 7        }        ///         /// The measure of area        ///         public enum EnumAcreageGroup        {            [EnumTitle("Unlimited", IsDisplay = false)]            None = 0,            [EnumTitle("The following 50mm")]            Below50 = 1,            [EnumTitle("50-70mm")]            From50To70 = 2,            [EnumTitle("70-90mm")]            From70To90 = 3,            [EnumTitle("90-120mm")]            From90To120 = 4,            [EnumTitle("120-150mm")]            From120To150 = 5,            [EnumTitle("150-200mm")]            From150To200 = 6,            [EnumTitle("200-300mm")]            From200To300 = 7,            [EnumTitle("More than 300mm")]            Above300 = 8        }        ///         /// Fangxing two chamber room five room five room above        ///         public enum EnumRoomGroup        {            [EnumTitle("Unlimited", IsDisplay = false)]            None = 0,            [EnumTitle("A room")]            Room1 = 1,            [EnumTitle("Room two")]            Room2 = 2,            [EnumTitle("3")]            Room3 = 3,            [EnumTitle("Four")]            Room4 = 4,            [EnumTitle("Room five")]            Room5 = 5,            [EnumTitle("More than five rooms")]            Above5 = 6        }    }}

Controller code[RadioBox]

ViewData.Add("EnumPriceGroup", new SelectList(EnumHelper.GetItemValueList
(), "Key", "Value")); ViewData.Add("EnumAcreageGroup", new SelectList(EnumHelper.GetItemValueList
(), "Key", "Value")); ViewData.Add("EnumRoomGroup", new SelectList(EnumHelper.GetItemValueList
(), "Key", "Value"));

View code[RadioBox]

@Html.RadioBoxList("EnumPriceGroup")@Html.RadioBoxList("EnumAcreageGroup")@Html.RadioBoxList("EnumRoomGroup")

Controller code[CheckBox]

TagRepository tagrep = new TagRepository();

 

var tag = tagrep.GetModelList().Where(d=>d.TypeID==1);            ViewBag.Tags = new SelectList(tag, "TagID", "TagName");            var tag1 = tagrep.GetModelList().Where(d => d.TypeID == 2);            ViewBag.Tags1 = new SelectList(tag1, "TagID", "TagName");            var tag2 = tagrep.GetModelList().Where(d => d.TypeID == 3);            ViewBag.Tags2 = new SelectList(tag2, "TagID", "TagName");
///         /// Add GET: /admin/House/Add        ///         /// The entity class        ///         /// 
[Authorize, HttpPost, ValidateInput(false)] public ActionResult Add(House model, FormCollection fc,int[] Tags, int[] Tags1,int[] Tags2) { model.State = 1; model.CreateTime = DateTime.Now; HouseControllerrep.SaveOrEditModel(model); if (Tags.Length > 0) { foreach (int gsi in Tags){ TagHouseMapping thmtag = new TagHouseMapping(); thmtag.TagID=gsi; thmtag.HouseID = model.HouseID; thmtag.State = 1; thmtag.CreateTime = DateTime.Now; TagCrep.SaveOrEditModel(thmtag); } } if (Tags1.Length > 0) { foreach (int gsi in Tags1) { TagHouseMapping thmtag = new TagHouseMapping(); thmtag.TagID = gsi; thmtag.HouseID = model.HouseID; thmtag.State = 1; thmtag.CreateTime = DateTime.Now; TagCrep.SaveOrEditModel(thmtag); } } if (Tags2.Length > 0) { foreach (int gsi in Tags2) { TagHouseMapping thmtag = new TagHouseMapping(); thmtag.TagID = gsi; thmtag.HouseID = model.HouseID; thmtag.State = 1; thmtag.CreateTime = DateTime.Now; TagCrep.SaveOrEditModel(thmtag); } } return RedirectToAction("Index"); } #endregion

View code[CheckBox]

@Html.CheckBoxList("Tags") @Html.CheckBoxList("Tags1") @Html.CheckBoxList("Tags2")

 

The effect of CheckBoxList

The effect of RadioBoxList

转自:

转载地址:http://awlpa.baihongyu.com/

你可能感兴趣的文章
Object-C---&gt;Swift之(七)嵌套函数与闭包
查看>>
css继承样式怎么控制?用选择器
查看>>
Http和Https三次握手那些事
查看>>
WCF 添加 RESTful 支持,适用于 IIS、Winform、cmd 宿主
查看>>
105.4. Installing Ganglia on Centos
查看>>
Drupal 曝出代码执行高危漏洞,数百万网站受影响
查看>>
SAP MM 移动类型107和109之研究
查看>>
SAP MM 系统确定供应源优先级
查看>>
交货单打印时提示“没有输出被选择打印”
查看>>
UML在软件开发各个阶段的应用
查看>>
服务器硬件问题整理的一点总结
查看>>
MSSQL · 实现分析 · Extend Event实现审计日志对SQL Server性能影响
查看>>
互动报表 SAP ABAP
查看>>
11.10. loop devices
查看>>
菜鸟学算法--简单的交换和最大公约数算法入门篇
查看>>
SAP S/4HANA Cloud: Revolutionizing the Next Generation of Cloud ERP
查看>>
《分歧者3》观后感
查看>>
GIS基础软件及操作(九)
查看>>
10天学安卓-第一天
查看>>
view和activity的区别(转)
查看>>