Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HtmlHelper and htmlAttributes help

I'm fairly new to MVC 3 and am using the Razor view engine. I'm using the Html.Hidden extension method to output input elements of type hidden. What I woudl also like to do is add a custom attribute to hold a dynamic value. I was under the impression in HTML5 wee could write custom html element attributes that are prefixed with 'data-'. I'm trying to do something like below;

@Html.Hidden("hdnID", mymodel.somevalue, new { data-uniqueid = mymodel.somevalue })

hoping to render;

<input type="hidden" value="mymodel.somevalue" data-uniqueid="mymodel.somevalue"/>

The htmlAttributes part (new { data-uniqueid = mymodel.somevalue }) is giving the error,

"Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignment, simple name or member access".

Can I add user-defined attribute to html elements using the HtmlHelper classes?

Regards,

like image 411
Jez Avatar asked Jun 28 '11 07:06

Jez


People also ask

What is the purpose of HtmlHelper class?

The HtmlHelper class renders HTML controls in the razor view. It binds the model object to HTML controls to display the value of model properties into those controls and also assigns the value of the controls to the model properties while submitting a web form.

What is an HtmlHelper?

An HTML Helper is just a method that returns a HTML string. The string can represent any type of content that you want. For example, you can use HTML Helpers to render standard HTML tags like HTML <input>, <button> and <img> tags etc.

How do you give ID in Razor syntax?

Just add the id property to the html-attributes. That will override the default id generated by the editorfor-helper-methode.


1 Answers

Use:

@Html.Hidden("hdnID", mymodel.somevalue, new { @data_uniqueid = mymodel.somevalue })

The underscore gets automatically converted to a dash.

like image 106
mccow002 Avatar answered Sep 18 '22 18:09

mccow002