HtmlHelper and htmlAttributes Help

I am new to MVC 3 and use the Razor viewer. I use the Html.Hidden extension method to display hidden input element types. What I would also like to do is add a custom attribute to hold the dynamic value. I was impressed with HTML5, we could write custom attributes for the html element that have the prefix "data-". I am trying to do something like below;

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

in the hope of rendering;

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

The htmlAttributes part (new {data-uniqueid = mymodel.somevalue}) gives an error,

"Invalid member declarator of anonymous type. Members of anonymous type must be declared with member assignment, simple name or member access."

Is it possible to add a user defined attribute to html elements using HtmlHelper classes?

Hi,

+6
source share
3 answers

Doh! I was stupid. You cannot have a "-" in a declaration like anon:

data-uniqueid = ... it must be

datauniqueid = ....

In this case, it is best to write hidden input manually:

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

Using:

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

The underscore is automatically converted to a dash.

+19
source

You can validate an element by creating a dictionary object. As below:

 @Html.TextBoxFor(model => model.Phone, new Dictionary<string, object> { { "data-call-results-target", "#search-results-area" }, { "data-action-path", "/Controler/Method" } }) 
0
source

Source: https://habr.com/ru/post/891523/


All Articles