简体   繁体   中英

LabelFor not working as expected

I am trying to create labels dynamically according to the number of items in a collection.

My model is passed to my view fine, however when iterating through the collection - i can't get the labels to display the values of the list of string.

For example i am using the following code:

  @foreach (var ac in model.myClass.listofstring)
           {
               @Html.LabelFor(a => ac)
           }

If the collection has 4 items, the above code will output "acacacac" I would like it to output 4 labels, with the string values of the items in the list.

I have also tried @Html.LabelFor(a => ac.ToString()) and @Html.LabelFor(a => ac.ToString) but the view then doesn't render.

I know the values are in the list as i can access them in my controller. The value of test is what i want in my view.

   foreach (var ac in myClass.listofstring)
       {
          var test = ac.ToString();
       }

I have also tried this, with no luck:

   @for (var i = 0; i < model.myClass.listofstring.Count(); i++)
           {
               @Html.LabelFor(a => a[i])
           }

Label isn't displaying the value of the item, it's just displaying its name. Use @Html.DisplayFor instead

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