doublej42

DropDownFillerFor

May 9th, 2014
531
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 7.62 KB | None | 0 0
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.ComponentModel;
  5. using System.Globalization;
  6. using System.Linq;
  7. using System.Linq.Expressions;
  8. using System.Text;
  9. using System.Web;
  10. using System.Web.Mvc;
  11. using System.Web.Mvc.Html;
  12. using System.Web.Mvc.Resources;
  13. using System.Web.Routing;
  14.  
  15.  
  16. namespace yourNamespace
  17. {
  18.  
  19.     /// <summary>
  20.     /// Dropfiller is a drop down menu that will auto fill other fields based on it's selected value
  21.     /// </summary>
  22.     public static class DropFiller
  23.     {
  24.  
  25.         internal static IDictionary<string, object> ObjectToDictionary(object instance)
  26.         {
  27.             IDictionary<string, object> propertyDictionary = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
  28.             if (instance != null)
  29.             {
  30.                 foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(instance))
  31.                 {
  32.                     object obj2 = descriptor.GetValue(instance);
  33.                     propertyDictionary.Add(descriptor.Name, obj2);
  34.                 }
  35.             }
  36.             return propertyDictionary;
  37.         }
  38.  
  39.  
  40.         public static int EditorForIndex(this HtmlHelper htmlHelper)
  41.         {
  42.             var start = htmlHelper.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix.LastIndexOf("[", StringComparison.Ordinal) + 1;
  43.             var end = htmlHelper.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix.LastIndexOf("]", StringComparison.Ordinal);
  44.             var strNumber = htmlHelper.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix.Substring(start, end - start);
  45.             int ret;
  46.             if (int.TryParse(strNumber,out ret))
  47.             {
  48.                 return ret;
  49.             }
  50.             return -1;
  51.         }
  52.         public static MvcHtmlString Idify(this HtmlHelper htmlHelper,string id)
  53.         {
  54.             return new MvcHtmlString(TagBuilder.CreateSanitizedId(htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(id)));
  55.         }
  56.  
  57.         public static MvcHtmlString GetDropDownFillerForTagID<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper,Expression<Func<TModel, TProperty>> expression)
  58.         {
  59.             var name = ExpressionHelper.GetExpressionText(expression);
  60.             return new MvcHtmlString(htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(name));
  61.         }
  62.          public static MvcHtmlString DropDownFillerFor<TModel, TProperty, T2Model>(this HtmlHelper<TModel> htmlHelper,
  63.             Expression<Func<TModel, TProperty>> expression,
  64.             IEnumerable<T2Model> objectList,
  65.             Expression<Func<T2Model, string>> valueExp,
  66.             Expression<Func<T2Model, string>> textExp,
  67.             List<SelectListItem> optionLabels,
  68.             object htmlAttributes)
  69.          {
  70.  
  71.              return htmlHelper.DropDownFillerFor(expression, objectList, valueExp, textExp, optionLabels, ObjectToDictionary(htmlAttributes));
  72.          }
  73.  
  74.         public static MvcHtmlString DropDownFillerFor<TModel, TProperty, T2Model>(this HtmlHelper<TModel> htmlHelper,
  75.             Expression<Func<TModel, TProperty>> expression,
  76.             IEnumerable<T2Model> objectList,
  77.             Expression<Func<T2Model, string>> valueExp,
  78.             Expression<Func<T2Model, string>> textExp,
  79.             List<SelectListItem> optionLabels = null,
  80.             IDictionary<string, object> htmlAttributes = null)
  81.         {
  82.             var textFunc = textExp.Compile();
  83.             var valueFunc = valueExp.Compile();
  84.             var name = ExpressionHelper.GetExpressionText(expression);
  85.  
  86.             string fullName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name);
  87.             string localname = fullName.Substring(htmlHelper.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix.Length + 1);
  88.             if (String.IsNullOrEmpty(fullName))
  89.             {
  90.                 throw new ArgumentException("Name Error", "expression");
  91.             }
  92.  
  93.             var defaultValue = GetModelStateValue(localname, typeof(string), htmlHelper);
  94.             if (defaultValue == null)
  95.             {
  96.                 defaultValue = string.Empty;
  97.             }
  98.             //object defaultValue =  htmlHelper.GetModelStateValue(fullName, typeof(string));
  99.  
  100.  
  101.            
  102.             // Convert each ListItem to an <option> tag
  103.             StringBuilder listItemBuilder = new StringBuilder();
  104.             var jsonSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
  105.             if (optionLabels != null)
  106.             {
  107.                 foreach (var item in optionLabels)
  108.                 {
  109.                     TagBuilder builder = new TagBuilder("option")
  110.                                              {
  111.                                                  InnerHtml = item.Text.Trim()
  112.                                              };
  113.                     builder.Attributes["value"] = item.Value;
  114.                     if (builder.Attributes["value"] == defaultValue.ToString())
  115.                     {
  116.                         item.Selected = true;
  117.                     }
  118.                     if (item.Selected)
  119.                     {
  120.                         builder.Attributes["selected"] = "selected";
  121.                     }
  122.                     listItemBuilder.AppendLine(builder.ToString(TagRenderMode.Normal));
  123.                 }
  124.             }
  125.            
  126.            
  127.  
  128.             foreach (var o in objectList)
  129.             {
  130.                 TagBuilder builder = new TagBuilder("option")
  131.                 {
  132.                     InnerHtml = HttpUtility.HtmlEncode(textFunc(o))
  133.                 };
  134.                 builder.Attributes["value"] = valueFunc(o);
  135.                 if (builder.Attributes["value"] == defaultValue.ToString())
  136.                 {
  137.                     builder.Attributes["selected"] = "selected";
  138.                 }
  139.                 builder.Attributes["data-jsonencoded"] = jsonSerializer.Serialize(o);
  140.  
  141.                 listItemBuilder.AppendLine(builder.ToString(TagRenderMode.Normal));
  142.  
  143.             }
  144.  
  145.             TagBuilder tagBuilder = new TagBuilder("select")
  146.             {
  147.                 InnerHtml = listItemBuilder.ToString()
  148.             };
  149.             tagBuilder.MergeAttributes(htmlAttributes);
  150.             tagBuilder.MergeAttribute("name", fullName, true /* replaceExisting */);
  151.             tagBuilder.GenerateId(fullName);
  152.             tagBuilder.MergeAttributes(htmlHelper.GetUnobtrusiveValidationAttributes(name));
  153.             return new MvcHtmlString(tagBuilder.ToString(TagRenderMode.Normal));
  154.  
  155.         }
  156.  
  157.         internal static string ListItemToOption(SelectListItem item)
  158.         {
  159.             TagBuilder builder = new TagBuilder("option")
  160.             {
  161.                 InnerHtml = HttpUtility.HtmlEncode(item.Text)
  162.             };
  163.             if (item.Value != null)
  164.             {
  165.                 builder.Attributes["value"] = item.Value;
  166.             }
  167.             if (item.Selected)
  168.             {
  169.                 builder.Attributes["selected"] = "selected";
  170.             }
  171.             return builder.ToString(TagRenderMode.Normal);
  172.         }
  173.  
  174.  
  175.         internal static object GetModelStateValue<TModel>(string key, Type destinationType, HtmlHelper<TModel> htmlHelper)
  176.         {
  177.             ModelState modelState;
  178.             if (htmlHelper.ViewContext.ViewData.ModelState.TryGetValue(key, out modelState))
  179.             {
  180.                 if (modelState.Value != null)
  181.                 {
  182.                     return modelState.Value.ConvertTo(destinationType, null /* culture */);
  183.                 }
  184.             }
  185.             return htmlHelper.ViewContext.ViewData.Eval(key);
  186.  
  187.         }
  188.      
  189.     }
  190.  
  191. }
Advertisement
Add Comment
Please, Sign In to add comment