I have a Custom Helper where I receive a htmlAttributes as 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 must return the merged htmlAttributes received in parameter with "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 an example field I need to add some 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 at last line in Editor Template is:
Click here to see the image
Note that the "class" is appearing correctly, but the others attributes from the Extension Helper are in a Dictionary, what am I doing wrong?
If possible, I want to change only Extension Helper and not Editor Template, so I think the RouteValueDictionary passed to EditorFor need to cast to a anonymous object...
I solved for now changing all my Editor Templates the line:
var htmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(ViewData["htmlAttributes"]);
for this:
var htmlAttributes = ViewData["htmlAttributes"] as IDictionary<string, object> ?? HtmlHelper.AnonymousObjectToHtmlAttributes(ViewData["htmlAttributes"]);
and the MergeAnonymous method to this:
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With