Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC 6 Tag Helpers and foreach

What would I give to asp-for property of a label tag helper in order to display items from a collection. The code below generates a compilation error.

@foreach (var item in Model)
{
    <label asp-for="item.BookingCode"></label>
}
like image 838
Sergey Kandaurov Avatar asked Aug 09 '15 11:08

Sergey Kandaurov


People also ask

What are tag helpers in MVC?

What is Tag Helper? Tag Helper is a new feature in ASP.NET MVC 6 that enables the server-side code to create and render HTML elements, in MVC Razor View files. These are the objects which can be bound to the Models and based on these properties, HTML elements can be dynamically rendered.

What is the difference between Htmlhelper and Taghelper?

Unlike HtmlHelpers, a tag helper is a class that attaches itself to an HTML-compliant element in a View or Razor Page. The tag helper can, through its properties, add additional attributes to the element that a developer can use to customize the tag's behavior.

Can we disable tag helper at the element level?

The opt-out character (“!”) is used to disable the Tag Helper at the element level. With the opt-out character, the HTML will not be generated for the label tag in the above case. We can use this opt-out character if we want to conditionally control rendering of the HTML elements.

What are tag helpers?

A Tag Helper Component is a Tag Helper that allows you to conditionally modify or add HTML elements from server-side code. This feature is available in ASP.NET Core 2.0 or later. ASP.NET Core includes two built-in Tag Helper Components: head and body . They're located in the Microsoft. AspNetCore.


1 Answers

The @ character escapes the default model lambda code. Therefore you can type:

@foreach (var item in Model)
{
    <label asp-for="@item.BookingCode"></label>
}
like image 185
N. Taylor Mullen Avatar answered Oct 19 '22 01:10

N. Taylor Mullen