Passing an object to HTML attributes

59,430

Solution 1

This functionality is, surprisingly enough, provided by the RouteValueDictionary class:

IDictionary<string, object> htmlAttributes = new RouteValueDictionary(attrs);

You can then use this dictionary in conjunction with a TagBuilder, which you will probably be using anyway:

var tagBuilder = new TagBuilder("input");
tagBuilder.MergeAttributes(htmlAttributes);
tagBuilder.ToString(TagRenderMode.Normal);

You can see this done in the ASP.NET MVC source code itself; one of the simpler examples is in TextAreaExtensions.cs.

EDIT:

In order to properly convert "data_attr" to "data-attr", use the AnonymousObjectToHtmlAttributes static method.

IDictionary<string, object> htmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(attrs);

Solution 2

You do not need to convert to a string. The last paramater for HTML Helpers is an Object. You just give it the object like you have written above:

For exmample

@Html.TextBoxFor(x => x.Foo, new { size = 10, maxlength = 10 }) 
@Html.TextAreaFor(x => x.Notes, new { @class = "additionalInfo" })
@Html.TextBoxFor(x=>x.Registration.Address.Postcode, new {type="number", @class="postcode numeric", size=5, maxlength=5})

on a side note you probably should not be setting styles directy inline with your HTML and use a CSS class/selector instead with a seperate style sheet. Also the ID of each DOM element should automatically be set when you use MVC HTML helpers

Solution 3

Here's how to do this conversion :

var htmlAttributes = new { id="myid", @class="myclass" };

string string_htmlAttributes = "";
foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(htmlAttributes))
{
  string_htmlAttributes += string.Format("{0}=\"{1}\" ", property.Name.Replace('_', '-'), property.GetValue(htmlAttributes));
}

PropertyDescriptor belong to the class System.ComponentModel

Share:
59,430

Related videos on Youtube

Hieu Nguyen Trung
Author by

Hieu Nguyen Trung

I'm a .Net Developer

Updated on August 23, 2020

Comments

  • Hieu Nguyen Trung
    Hieu Nguyen Trung over 3 years

    How to pass an object to HTML attributes? For example I have the following code:

    var attrs = new { id = "myid", style = "color: Red;" };
    

    How to convert attrs to string like this to embed them into an HTML markup:

    id="myid" style="color: Red;"
    

    Thanks in advance :)

    • Sergey
      Sergey over 11 years
      Thank you for you question! I saved my day!
  • Hieu Nguyen Trung
    Hieu Nguyen Trung almost 13 years
    I know, but in addition, i want to write my own method to render another form component, so i need a way to do it like MVC 3 did :)
  • Daveo
    Daveo almost 13 years
    np you problably should of mentioned that in your question
  • SimonGates
    SimonGates almost 11 years
    Just tries this with the attribute data_bind and the output was data_bind as opposed to the expected, data-bind - any ideas?
  • slawek
    slawek almost 11 years
    Unfortunately Url to TextAreaExtensions is no longer valid :) Just letting you know.
  • Adrian Wragg
    Adrian Wragg almost 11 years
    There's an alternative, System.Web.Mvc.HtmlHelper.AnonymousObjectToHtmlAttributes(), that may be more appropriate; it replaces underscores with hyphens in the same manner as the standard MVC Html helpers
  • Joel
    Joel over 9 years
    This answer is obsolete. The correct approach should be HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes) which will properly handle data_blah type attributes.
  • Eric
    Eric over 8 years
    No idea why this isn't the recommended answer.
  • Liviu
    Liviu over 8 years
    the code is ok with an important change: use HttpUtility.HtmlAttributeEncode to render the attribute value.
  • Liviu
    Liviu over 8 years
    also convert tag names x_y in x-y. This is how TagBuilder does it.