How to merge htmlAttributes into user helper

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

+5
source share
2 answers

I decided to change all my editor templates to a line:

 var htmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(ViewData["htmlAttributes"]); 

for this:

 var htmlAttributes = ViewData["htmlAttributes"] as IDictionary<string, object> ?? HtmlHelper.AnonymousObjectToHtmlAttributes(ViewData["htmlAttributes"]); 

and MergeAnonymous method:

 static IDictionary<string,object> MergeAnonymous(object obj1, object obj2) { var dict1 = new RouteValueDictionary(obj1); var dict2 = new RouteValueDictionary(obj2); IDictionary<string, object> result = new Dictionary<string, object>(); foreach (var pair in dict1.Concat(dict2)) { result.Add(pair); } return result; } 
+4
source
 public static class CustomHelper { public static MvcHtmlString Custom(this HtmlHelper helper, string tagBuilder, object htmlAttributes) { var builder = new TagBuilder(tagBuilder); RouteValueDictionary customAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes); foreach (KeyValuePair<string, object> customAttribute in customAttributes) { builder.MergeAttribute(customAttribute.Key.ToString(), customAttribute.Value.ToString()); } return MvcHtmlString.Create(builder.ToString(TagRenderMode.SelfClosing)); } } 
0
source

Source: https://habr.com/ru/post/1204219/


All Articles