Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing an object to HTML attributes

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 :)

like image 784
Hieu Nguyen Trung Avatar asked Jun 22 '11 04:06

Hieu Nguyen Trung


People also ask

How to embed objects in HTML?

The <object> tag defines a container for an external resource. The external resource can be a web page, a picture, a media player, or a plug-in application. To embed a picture, it is better to use the <img> tag. To embed HTML, it is better to use the <iframe> tag.

How do I create a custom attribute in HTML?

If you want to define your own custom attributes in HTML, you can implement them through data-* format. * can be replaced by any of your names to specify specific data to an element and target it in CSS, JavaScript, or jQuery.

What are the 3 types of attribute in HTML?

HTML attributes are generally classified as required attributes, optional attributes, standard attributes, and event attributes: Usually the required and optional attributes modify specific HTML elements.


2 Answers

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); 
like image 69
Domenic Avatar answered Sep 29 '22 05:09

Domenic


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

like image 42
Daveo Avatar answered Sep 29 '22 04:09

Daveo