Search code examples
c#asp.net-mvcrazormvc-editor-templates

How propagate HTMLAttributes to a custom EditorTemplate?


I created a Editor template for currency float format like this.

@using System.Globalization
@{
    var ri = new RegionInfo(System.Threading.Thread.CurrentThread.CurrentUICulture.LCID);
}

<div class="input-group ">
    <div class="input-group-addon">@ri.CurrencySymbol</div>
    @Html.TextBox("", ViewData.ModelMetadata.Model, new { @class = " form-control text-box single-line" })
</div>

which shows a bootstrap input group with currency symbol

enter image description here

It works fine, but im trying to pass some additional classes like "text-danger" or "input-group-lg" however those parameters are not passed to the Editor template.

@Html.EditorFor(model => model.money, new { htmlAttributes = new { @class = "text-danger input-lg form-group-lg" } })

the classes "text-danger input-lg form-group-lg" are not set to the main div.

How can I propagate those classes to my Editor template?


Solution

  • Just use route ViewData["htmlAttributes"] to a dictionary and get "class" value

    @{
        var htmlAttrib = ViewData["htmlAttributes"]
        IDictionary<string, object> dic = new RouteValueDictionary(htmlAttrib);
        var classes = dic ["class"];
    }
    
    <div class="@classes" > your control .... </div>