How to get HtmlAttributes in custom EditTemplate

in MVC5

Dienstag, 17. März 2015

Assume you habe a view using Html.EditorFor like this:

@Html.EditorFor(model => model, 
   new { htmlAttributes = new { @data_test = "value" } })

and have a EditTemplate which needs to add the attributes:

@model int?
 var htmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(ViewData["htmlAttributes"]);
 htmlAttributes.Add("class", "myclass"); 
<div class="justsomething">
 @Html.Hidden("", Model, htmlAttributes)

Which results in

<div class="justsomething">
<input type="hidden" data-test="value" value=""/>