Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding HtmlAttributes to template

If I am passing HtmlAttributes into a template, like this:

@Html.DisplayFor(m => m.FirstName, new { htmlAttributes = new { @class = "orangetxt strongtxt" } })

In my template, how would I inject these into my HTML:

<span @ViewData["htmlAttributes"]>@Model</span>

This almost works, but it does some pretty weird stuff, so I'm assuming this isn't the way to go.

I realize I can accomplish this with an HtmlHelper extension method to render the full HTML element (span, in this case) and pass in the attributes that way, but is there a way to just render attributes straight into an HTML element, like the above example?

like image 491
Jerad Rose Avatar asked Oct 19 '11 23:10

Jerad Rose


People also ask

What does HTML EditorFor do?

The Html. Editor() or Html. EditorFor() extension methods generate HTML elements based on the data type of the model object's property.


1 Answers

The below extension method will allow me to convert HtmlAttributes to a string:

    public static MvcHtmlString RenderHtmlAttributes<TModel>(
        this HtmlHelper<TModel> htmlHelper, object htmlAttributes)
    {
        var attrbituesDictionary = new RouteValueDictionary(htmlAttributes);

        return MvcHtmlString.Create(String.Join(" ", 
            attrbituesDictionary.Select(
                item => String.Format("{0}=\"{1}\"", item.Key, 
                htmlHelper.Encode(item.Value)))));
    }

Then, to render them within the tag, I can just do this:

<span @Html.RenderHtmlAttributes(ViewData["htmlAttributes"])>@Model</span>
like image 90
Jerad Rose Avatar answered Oct 10 '22 08:10

Jerad Rose