I have a custom helper where I get the htmlAttributes parameter as a parameter:
public static MvcHtmlString Campo<TModel, TValue>( this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression, dynamic htmlAttributes = null) { var attr = MergeAnonymous(new { @class = "form-control"}, htmlAttributes); var editor = helper.EditorFor(expression, new { htmlAttributes = attr }); ... }
The MergeAnonymous method should return the combined htmlAttributes obtained in the parameter using "new {@ class =" form-control "}":
static dynamic MergeAnonymous(dynamic obj1, dynamic obj2) { var dict1 = new RouteValueDictionary(obj1); if (obj2 != null) { var dict2 = new RouteValueDictionary(obj2); foreach (var pair in dict2) { dict1[pair.Key] = pair.Value; } } return dict1; }
And in the Editor Template for the example field, I need to add a few more attributes:
@model decimal? @{ var htmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(ViewData["htmlAttributes"]); htmlAttributes["class"] += " inputmask-decimal"; } @Html.TextBox("", string.Format("{0:c}", Model.ToString()), htmlAttributes)
What I have in htmlAttributes in the last line in the editor template:
Click here to see the image.
Please note that the βclassβ is displayed correctly, but the rest of the attributes from the extension helper are contained in the dictionary, what am I doing wrong?
If possible, I want to change only the Extension Helper, not the Editor Template, so I think that the RouteValueDictionary passed to EditorFor needs to be sent to an anonymous object ...