2011年2月23日水曜日

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

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

using System.Web.Mvc.Html;
using System.Linq.Expressions;

public static class CustomTextBoxHelper
{   
 public static MvcHtmlString BlueTextBoxFor<TModel, TProperty>(
  this HtmlHelper<TModel> htmlHelper, 
  Expression<Func<TModel, TProperty>> expression
   )
   {
     var htmlAttributes = new Dictionary<string, object>();

     htmlAttributes.Add("style", "background-color: skyblue;");

     return InputExtensions.TextBoxFor<TModel, TProperty>(
      htmlHelper, 
      expression, 
      htmlAttributes) ;       
    }
 }

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

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

0 件のコメント:

コメントを投稿