andrew4582

HttpContextExtentions

Aug 18th, 2010
230
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.05 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.Caching;
  6. using System.Web.Mvc;
  7.  
  8. namespace Core.Web {
  9.  
  10.     public static class HttpContextExtentions {
  11.  
  12.         public static T GetOrAdd<T>(this HttpContext context,object key,Func<T> notFoundFunc = null) {
  13.  
  14.             if(key == null)
  15.                 throw new ArgumentNullException("object key");
  16.  
  17.             T result = (T)context.Items[key];
  18.  
  19.             if(result == null) {
  20.                 if(notFoundFunc != null) {
  21.                     result = notFoundFunc();
  22.                     context.Items.Add(key,result);
  23.                     return result;
  24.                 }
  25.                 return default(T);
  26.             }
  27.             return result;
  28.         }
  29.     }
  30.     public static class HtmlHelperExtentions {
  31.         public static IDictionary<string,object> GetClassAttribute(this HtmlHelper html,string className,IDictionary<string,object> additionalAttributes = null) {
  32.  
  33.             IDictionary<string,object> dict = null;
  34.             if(additionalAttributes != null)
  35.                 dict = new Dictionary<string,object>(additionalAttributes);
  36.             else
  37.                 dict = new Dictionary<string,object>();
  38.  
  39.             object previousClassName = null;
  40.             if(dict.TryGetValue("class",out previousClassName)) {
  41.                 dict["class"] = previousClassName.ToStringEmpty() + " " + className;
  42.             }
  43.             else {
  44.                 dict.Add("class",className);
  45.             }
  46.            
  47.             return dict;
  48.         }
  49.         public static MvcHtmlString WrapEmailAnchor(this HtmlHelper html,string innerHtml,string nameAndId = null,string title = null) {
  50.             TagBuilder anchor = new TagBuilder("a");
  51.             anchor.GenerateId(nameAndId);
  52.             anchor.MergeAttribute("href","mailto:{0}".FormatString(innerHtml));
  53.             anchor.MergeAttribute("title",title);
  54.             anchor.InnerHtml = innerHtml;
  55.             return MvcHtmlString.Create(anchor.ToString());
  56.         }
  57.     }
  58. }
Advertisement
Add Comment
Please, Sign In to add comment