Month: October 2014

Rendering HTML5 data attribute in MVC

The HTML5 data attribute is data-* attribute which can be used to store extra information about the rendering element. If you are using 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,


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. 🙂