LoginSignup
5
7

More than 5 years have passed since last update.

input要素用のid属性とname属性の値を取得する

Last updated at Posted at 2015-01-15

EditorTemplateなどでヘルパーを使わずにinput要素を出力したい時がありますが、id属性とname属性の値をどう調達すれば良いのか悩みます。フィールドは入れ子になっていたり配列になっていたりする場合があるので決め打ちで書くことはできません。

ASP.NET MVC 4以降であればIdForヘルパーとNameForヘルパーが用意されているのでそれを使えばよいです。

<input type="text" id="@Html.IdFor(m => m.Example)" name="@Html.NameFor(m => m.Example)" />

そうではない残念な環境やヘルパーが使えない場合などは以下のようにして取得します。

@{
    var name = ExpressionHelper.GetExpressionText(m => m.Example);
    var id = ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(name);
    var fullName = ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name);
}
<input type="text" id="@id" name="@fullName" />

参考
* MSDN: NameExtensions.IdFor メソッド
* MSDN: NameExtensions.NameFor メソッド
* MSDN: ExpressionHelper.GetExpressionText メソッド
* MSDN: TemplateInfo.GetFullHtmlFieldId メソッド
* MSDN: TemplateInfo.GetFullHtmlFieldName メソッド

5
7
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
5
7