Alex Rivera | Logout

Passing an object to HTML attributes

Asked 2011-06-22T04:22:10.787
43

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

Edit
Report

1 Answer

24

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

answered 2011-06-22T04:28:29.487

Your Answer