ASP.NET MVC HtmlHelper Razor Syntax
I am currently learning ASP.NET MVC and the following piece of code is presented:
@Html.TextBoxFor(m => m.FirstName, new { @placeholder = "First name"})
I understand that the lambda expression refers to the model as m , but what is the second argument? It seems to be an anonymous type, but my main question is, why is there an @ symbol in front of the subscriber ?
source to share
The second argument htmlAttributes
you can use to add additional attributes to the HTML generated by the helper (@ Html.TextBoxFor is the HTML helper).
The generated code for your example will look like this:
@Html.TextBoxFor(m => m.FirstName, new { @placeholder = "First name"})
<input type="text" name="FirstName" placeholder="First name" />
If you want, you can add more attributes and they will be added to the generated tag as well:
@Html.TextBoxFor(m => m.FirstName, new { placeholder = "First name", @class="my_text_box_class" })
<input type="text" name="FirstName" placeholder="First name" class="my_text_box_class" />
It is also possible to override the textbox value with Value
(uppercase V!):
@Html.TextBoxFor(m => m.FirstName, new { placeholder = "First name", Value="John Johnson"})
<input type="text" name="FirstName" placeholder="First name" value="John Johnson" />
The reason for the @ symbol is that you want to get an attribute named exactly like the C # reserved word . class, private, namespace, etc. This is a way to make the C # interpreter stop interpreting it as a C # value. The @ symbol is only required for these reserved words.
source to share
The syntax @placeholder
tells the razor engine that you want to assign a value to the html attribute for the element that the helper will render. This way, if you needed to set a class on a textbox, your anonymous type would change to:
new { @placeholder = "First name", @class = "BoldText" }
In terms of usage @
, @
allows reserved keywords to be used as variable names. If you tried to use
class = "BoldText"
you will get a runtime error in your view as it class
is a reserved keyword in C #. Pre-processing @
ensures this does not happen and is considered "best practice". @
it would only be necessary before class
, not placeholder
.
source to share