简体   繁体   中英

ASP.NET MVC HtmlHelper Razor Syntax

I am currently learning ASP.NET MVC and am presented with the following code snippet:

@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 @ character in front of placeholder?

The second argument is htmlAttributes which you can use to add additional attributes to the HTML that is generated by the helper (@Html.TextBoxFor is a HTML helper).

The generated code for your example will be along the lines of:

@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 also be added to the generated tag:

@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's also possible to override the value of the textbox using Value (upper case 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 for when you want an attribute named exactly as a C# reserved word . class, private, namespace etc. It is a way to make the C# complier stop interpreting it as it's C# meaning. The @ symbol is only required for these reserved words.

The @placeholder syntax tells the razor engine that you want to assign a value to an html attribute on the element that will be rendered by the helper. As such, if you needed to set a class to the textbox as well, your anonymous type would change to:

new { @placeholder = "First name", @class = "BoldText" }

As for why you use @ , the @ allows you to use reserved keywords as variable names. If you tried to use

class = "BoldText"

you would receive a runtime error in your view since class is a reserved keyword in C#. The prefacing @ ensures that this doesn't happen and is considered a "best practice". The @ would only be necessary before class , not placeholder .

The second parameter expects an anonymous object for the htmlAttributes you would like to specify in your input.

You use the @ symbol to tell the razor engine that you're specifying an htmlAttribute and not a reserved keyword.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM