2011年2月23日水曜日

.NET MVC | カスタムHtmlヘルパーの作成

カスタムHtmlヘルパーの一例。拡張メソッドにより、HtmlHelperに追加にした。

  1. using System.Web.Mvc.Html;  
  2. using System.Linq.Expressions;  
  3.   
  4. public static class CustomTextBoxHelper  
  5. {     
  6.  public static MvcHtmlString BlueTextBoxFor<TModel, TProperty>(  
  7.   this HtmlHelper<TModel> htmlHelper,   
  8.   Expression<Func<TModel, TProperty>> expression  
  9.    )  
  10.    {  
  11.      var htmlAttributes = new Dictionary<stringobject>();  
  12.   
  13.      htmlAttributes.Add("style""background-color: skyblue;");  
  14.   
  15.      return InputExtensions.TextBoxFor<TModel, TProperty>(  
  16.       htmlHelper,   
  17.       expression,   
  18.       htmlAttributes) ;         
  19.     }  
  20.  }  

こんな感じで、cshtmlに記述できる。

  1. @Html.BlueTextBoxFor(x => x.text)  

0 件のコメント:

コメントを投稿