Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to merge htmlAttributes in Custom Helper

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

like image 658
Oswaldo Avatar asked Oct 07 '14 22:10

Oswaldo


1 Answers

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;
}
like image 78
Oswaldo Avatar answered Oct 20 '22 03:10

Oswaldo