Add HTML Properties to an input via Razor

Asked

Viewed 92 times

2

When I create a field input-type-text Via Razor, I do something like this:

@Html.TextBox("nomeTxt", null, new { @class = "form-control", 
                                     @placeholder = "Exemplo de placeholder",  
                                     @type = "text" })

When I want to add properties HTML That input, I put them as I did with the @class, @placeholder, @type

For example, if I want to put one MaxLength, just add to the end, as in:

@Html.TextBox("nomeTxt", null, new { @class = "form-control", 
                                     @placeholder = "Exemplo de placeholder", 
                                     @type = "text", 
                                     @maxlength="10" })

However, some types of properties I can’t add that way. This is the case with data-date-format. Razor can’t take these hyphens.

How could I create, via Razor, a input as the example below?

<input id="txtData" name="txtData" 
                    placeholder="Ex.: 13/10/2019" 
                    data-date-format="dd/mm/yyyy" 
                    maxlength="10">

1 answer

3


In this case you must exchange the hyphens for underscore.

Note that arrobas are unnecessary in attributes (apart from class), this operator is only used to name some reserved word of the language (class, int, string, etc..).

@Html.TextBox("nomeTxt", null, new { @class = "form-control", 
                                 placeholder = "Exemplo de placeholder", 
                                 type = "text",                                      
                                 maxlength="10" 
                                 data_date_format="dd/mm/yyyy" })
  • It worked perfect, thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.