简体   繁体   中英

Tag helpers in ASP.NET

I am learning ASP.NET Core with this tutorial .

I am now adding search funcionality, which requires passing data between Razor Page and underlying C# class. To achieve that, I am instructed to do it this way:

<select asp-for="MovieGenre" asp-items="Model.Genres">
   <option value="">All</option>
</select>

Of course, I have field Genres properly initalized, so the list is OK.

As I understand, in a attribute asp-for we specify target variable. It adds variable to query string in URL nicely, but it's pretty cumbersome, as I need field in underlying class, which name has to exaclty match. So, I have to have MovieGenre field. But what's the point if I only want to add it into query string? What is the idea behind it?

I came up with simplier approach:

<select name="movieGenre" asp-items="Model.Genres">
    <option value="">All</option>
</select>

which ONLY adds movieGenre=... to URL, without need to declare extra field in my class.

So, why would one use asp-for if we have much simplier name attribute?

The tag helper adds id and name based on the property name specified in the asp-for attribute. given this markup:

<input asp-for="Name" />

The Tag Helper above generates the following HTML:

<input type="text" id="Name" name="Name" />

As you can see, by using tag helper you don't need to write those properties anymore. they will be generate for you automatically.

It also gives you proper intellisense while you are coding. so it actually is a syntactic sugar for creating form elements.

more info ( + )

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