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<SelectListItem>, new { }, isHorizon); } public static MvcHtmlString CheckBoxList(this HtmlHelper helper, string name, IEnumerable<SelectListItem> selectList, bool isHorizon = true) { return CheckBoxList(helper, name, selectList, new { }, isHorizon); } public static MvcHtmlString CheckBoxListFor<TModel, TProperty>(this HtmlHelper helper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> 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<SelectListItem> 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<SelectListItem> selectList, object htmlAttributes, bool isHorizon = true) { IDictionary<string, object> HtmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes); HashSet<string> set = new HashSet<string>(); List<SelectListItem> list = new List<SelectListItem>(); 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 <tempStr.Length; i++) { set.Add(tempStr[i].Trim()); } } else { set.Add(selectedValues); } } foreach (SelectListItem item in selectList) { item.Selected = (item.Value != null) ? set.Contains(item.Value) : set.Contains(item.Text); list.Add(item); } selectList = list; HtmlAttributes.Add("type", "checkbox"); HtmlAttributes.Add("id", id); HtmlAttributes.Add("name", name); HtmlAttributes.Add("style", "border:none;"); StringBuilder stringBuilder = new StringBuilder(); foreach (SelectListItem selectItem in selectList) { IDictionary<string, object> newHtmlAttributes = HtmlAttributes.DeepCopy(); newHtmlAttributes.Add("value", selectItem.Value); if (selectItem.Selected) { newHtmlAttributes.Add("checked", "checked"); } TagBuilder tagBuilder = new TagBuilder("input"); tagBuilder.MergeAttributes<string, object>(newHtmlAttributes); string inputAllHtml = tagBuilder.ToString(TagRenderMode.SelfClosing); string containerFormat = isHorizon ? @"<label> {0} {1}</label>" : @"<p><label> {0} {1}</label></p>"; stringBuilder.AppendFormat(containerFormat, inputAllHtml, selectItem.Text); } return MvcHtmlString.Create(stringBuilder.ToString()); } private static IDictionary<string, object> DeepCopy(this IDictionary<string, object> ht) { Dictionary<string, object> _ht = new Dictionary<string, object>(); 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<SelectListItem>, new { }); } public static MvcHtmlString RadioBoxList(this HtmlHelper helper, string name, IEnumerable<SelectListItem> selectList) { return RadioBoxList(helper, name, selectList, new { }); } public static MvcHtmlString RadioBoxList(this HtmlHelper helper, string name, IEnumerable<SelectListItem> selectList, object htmlAttributes) { IDictionary<string, object> 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<string, object> 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<string, object>(newHtmlAttributes); string inputAllHtml = tagBuilder.ToString(TagRenderMode.SelfClosing); stringBuilder.AppendFormat(@" {0} <label for=‘{2}‘>{1}</label>", inputAllHtml, selectItem.Text, id); } return MvcHtmlString.Create(stringBuilder.ToString()); } private static IDictionary<string, object> DeepCopy(this IDictionary<string, object> ht) { Dictionary<string, object> _ht = new Dictionary<string, object>(); 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 { /// <summary> /// Enumeration helper classes /// </summary> public class EnumHelper { /// <summary> /// Such as: "enum1, enum2 conversion, enum3" string to the enumeration values /// </summary> /// <typeparam name="T">Enumeration types</typeparam> /// <param name="obj">The enumerated string</param> /// <returns></returns> public static T Parse<T>(string obj) { if (string.IsNullOrEmpty(obj)) return default(T); else return (T)Enum.Parse(typeof(T), obj); } public static T TryParse<T>(string obj, T defT = default(T)) { try { return Parse<T>(obj); } catch { return defT; } } public static readonly string ENUM_TITLE_SEPARATOR = ","; /// <summary> /// According to the enumeration value, return a string describing the /// If multiple enumeration, return to the "," separated string /// </summary> /// <param name="e"></param> /// <returns></returns> 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()); } /// <summary> /// According to the enumeration value, return a string describing the /// If multiple enumeration, return to the "," separated string /// </summary> /// <param name="e"></param> /// <returns></returns> 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 ""; } } /// <summary> /// Returns the key value pairs, built for the name of the specified enumeration of EnumTitle and synonym name, value is the enumeration entries /// </summary> /// <typeparam name="T">Enumeration types</typeparam> /// <param name="language"></param> /// <returns></returns> public static Dictionary<string, T> GetTitleAndSynonyms<T>(Enum language = null) where T : struct { Dictionary<string, T> ret = new Dictionary<string, T>(); //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; } /// <summary> /// 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 /// </summary> /// <returns></returns> public static Dictionary<T, string> GetItemList<T>(Enum language = null) where T : struct { return GetItemValueList<T, T>(false, language); } /// <summary> /// 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 /// </summary> /// <returns></returns> public static Dictionary<T, string> GetAllItemList<T>(Enum language = null) where T : struct { return GetItemValueList<T, T>(true, language); } /// <summary> /// Access to enumerate all the title, the text is composed by the application in the enumeration values on the EnumTitleAttribute set /// </summary> /// <typeparam name="T">Enumeration types</typeparam> /// <param name="language">Language</param> /// <returns></returns> public static Dictionary<int, string> GetItemValueList<T>(Enum language = null) where T : struct { return GetItemValueList<T, int>(false, language); } /// <summary> /// Access to enumerate all the title, the text is composed by the application in the enumeration values on the EnumTitleAttribute set /// </summary> /// <typeparam name="T">Enumeration types</typeparam> /// <param name="isAll">Whether to build the "all"</param> /// <param name="language">Language</param> /// <returns></returns> public static Dictionary<TKey, string> GetItemValueList<T, TKey>(bool isAll, Enum language = null) where T : struct { if (!typeof(T).IsEnum) { throw new Exception("The parameter must be enumerated!"); } Dictionary<TKey, string> ret = new Dictionary<TKey, string>(); var titles = EnumHelper.GetItemAttributeList<T>().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<T> GetItemKeyList<T>(Enum language = null) where T : struct { List<T> list = new List<T>(); Array array = typeof(T).GetEnumValues(); foreach (object t in array) { list.Add((T)t); } return list; } public static Dictionary<T, EnumTitleAttribute> GetItemAttributeList<T>(Enum language = null) where T : struct { if (!typeof(T).IsEnum) { throw new Exception("The parameter must be enumerated!"); } Dictionary<T, EnumTitleAttribute> ret = new Dictionary<T, EnumTitleAttribute>(); 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; } /// <summary> /// Access to enumerate all the title, the text is composed by the application in the enumeration values on the EnumTitleAttribute set /// </summary> /// <typeparam name="T">Enumeration types</typeparam> /// <param name="isAll">Whether to build the "all"</param> /// <param name="language">Language</param> /// <returns></returns> public static Dictionary<TKey, string> GetAllItemValueList<T, TKey>(Enum language = null) where T : struct { return GetItemValueList<T, TKey>(true, language); } /// <summary> /// Gets an enumeration pairs /// </summary> /// <typeparam name="TEnum">Enumeration types</typeparam> /// <param name="exceptTypes">Exclude the enumeration</param> /// <returns></returns> public static Dictionary<int, string> GetEnumDictionary<TEnum>(IEnumerable<TEnum> exceptTypes = null) where TEnum : struct { var dic = GetItemList<TEnum>(); Dictionary<int, string> dicNew = new Dictionary<int, string>(); 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; } /// <summary> /// Synonyms /// </summary> 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 { /// <summary> /// Gender /// </summary> public enum EnumSex { [EnumTitle("Hello, sir")] Sir = 1, [EnumTitle("Ma‘am")] Miss = 2 } /// <summary> /// Make an appointment /// </summary> public enum EnumBespeakDate { [EnumTitle("Working days (Monday to Friday)")] BespeakDate1 = 1, [EnumTitle("The weekend")] BespeakDate2 = 2, [EnumTitle("Weekdays or weekends")] BespeakDate3 = 3 } /// <summary> /// Appointments /// </summary> public enum EnumBespeakTime { [EnumTitle("Morning")] BespeakTime1 = 1, [EnumTitle("The afternoon")] BespeakTime2 = 2, [EnumTitle("Night")] BespeakDate3 = 3, [EnumTitle("At any time")] BespeakDate4= 4 } /// <summary> /// The price /// </summary> 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 } /// <summary> /// The measure of area /// </summary> 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 } /// <summary> /// Fangxing two chamber room five room five room above /// </summary> 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<EnumData.EnumPriceGroup>(), "Key", "Value")); ViewData.Add("EnumAcreageGroup", new SelectList(EnumHelper.GetItemValueList<EnumData.EnumAcreageGroup>(), "Key", "Value")); ViewData.Add("EnumRoomGroup", new SelectList(EnumHelper.GetItemValueList<EnumData.EnumRoomGroup>(), "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");
/// <summary> /// Add GET: /admin/House/Add /// </summary> /// <param name="model">The entity class</param> /// <param name="fc"></param> /// <returns></returns> [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://www.programering.com/a/MDN2AzNwATQ.html
时间: 2024-11-25 23:53:14