Rendering HTML5 data attribute in asp.net MVC

The HTML5 data attribute is data-* attribute which can be used to store extra information about the rendering element. If you are using asp.net MVC then most of the html helper takes htmlattribute object as parameter , this is special object which you can use to render the html attribute value. for example to render below html

<input id="employeeName" name="employeeName" type="text" accesskey="a" />

You can use MVC TextBox helper as below,

@Html.TextBox(“employeeName”,null,new { accesskey=”a”})

here we passing accesskey attribute to render the desired html. now support we want to render below html.

for it if we write data-leftpos as another attribute in TextBox helper method parameter then it is not going to compile since it is not a valid property name as below,

image 

To render the desired output you can pass these property name separated by underscore as below as MVC rendering engine automatically convert it to dash “-” as below,

@Html.TextBox(“employeeName”,null,new { accesskey=”a”, data_leftPos=100,data_topPos=10})

 

Thanks for reading, hope it helped. Happy Coding. 🙂 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s