28

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>
}
8
  • 1
    what is error and,in model i think you have collection of same item and all items will contain same attribute name for same value. Commented Aug 9, 2015 at 13:24
  • Yes, you're right. I was actually looking for a way to display values, but apparently MVC6 does not have tag helper for this yet. The error is that there is no "item" in scope, which makes sense because Model.item does not exist. Commented Aug 9, 2015 at 13:36
  • @ConvertToInt32 - actually even if I put <label> outside for foreach, I still don't get what should be in asp-for. My model is IEnumerable<>. Commented Aug 9, 2015 at 13:38
  • 1
    Instead of using IEnumerable<T> as your model try IList<T>. Commented Aug 11, 2015 at 7:11
  • 1
    You said your model is IEnumerable<>. Switch it to IList<> like adding '.ToList<>()' at the end, in code behind. Commented Sep 4, 2015 at 20:49

2 Answers 2

35

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

@foreach (var item in Model)
{
    <label asp-for="@item.BookingCode"></label>
}
Sign up to request clarification or add additional context in comments.

3 Comments

In 1.0.0-rc1-update1 the above code simply prints "BookingCode" text instead of the actual value of the BookingCode property. Any other solutions?
Since this is for a label element the asp-for defaults to the property name and not the value of BookingCode. Use @item.BookingCode with no element to see the value.
Tag helper for <label> will not be that important here. But if you wan to use it, as @JoelCunningham stated, use <label asp-for="@item.BookingCode">@item.BookingCode</label> asp-for value will display the heading as a property name and @item.BookingCode inside <label ...>...</label> will display the value of @item.BookingCode.
-4

I Have a simple way to do a list and show properties of it.

List<string> razones = new List<string>();
foreach (var item in _context.Reason)
{
    razones.Add (item.Description);
}
System.Diagnostics.Debug.WriteLine(razones.Count);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.