LoginSignup
4
3

More than 5 years have passed since last update.

EditorForでhtmlAttributesを指定できるようにする

Posted at

ASP.NET MVC 5からEditorForにadditionalViewDataを渡せるようになり、HTMLの属性などを指定できるように作れるようになりました。

受け取ったhtmlAttributesをそのまま指定するだけなら簡単ですが、エディターテンプレート側でclass属性などを付けている場合があり、そういう場合はパラメータとして受け取ったものとエディターテンプレートで付けようとしているものをマージしてやる必要があります。とはいえhtmlAttributesはおおむね匿名型で来るのでマージできない……

と思ったら、まさにそれ用のHtmlHelper.AnonymousObjectToHtmlAttributes()という匿名型をディクショナリに変換するメソッドがありました。

@Html.EditorFor(model => model, new { htmlAttributes = new { @class = "form-control" }, })
EditorTemplate/DateTime.cshtml
@model System.DateTime?
@{
    var htmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(ViewData["htmlAttributes"]);
    htmlAttributes.Add("class", "datepicker");
}
@Html.TextBox("", Model != null ? Model.Value.ToString("yyyy/MM/dd") : "", htmlAttributes)

参考)
http://msdn.microsoft.com/ja-jp/library/system.web.mvc.htmlhelper.anonymousobjecttohtmlattributes(v=vs.118).aspx

4
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3