How to implement foreach delegate in razor view?

The following code works for the web form viewer.

<% Model.Categories.ForEach(x => { %>
    <li><a href="#">@x.Name</a></li>
<% }) %>

I wrote the code above as shown below:

@Model.Categories.ForEach(x => {
  <li><a href="#">@x.Name</a></li>
})

But that will not work.

Can anyone suggest if there is a way to achieve this in razor mode?

Thanks in advance.

+3
source share
2 answers

Thank you for your help. I found how to implement delegates in Razor based on the next article by Phil Haack. Invited Razor Delegates

Here is the extension code for IEnumerable:

public static HelperResult ForEachTemplate<TEntity>(
        this IEnumerable<TEntity> items, 
        Func<RowEntity<TEntity>, HelperResult> template)
{
    return new HelperResult(writer =>
               {
                   var index = 0;
                   foreach (var item in items)
                   {
                       template(new RowEntity<TEntity> { 
                               Index = index, 
                               Value = item }).WriteTo(writer);
                       index++;
                   }
               });
}

public class RowEntity<TEntity>
{
    public int Index { get; set; }
    public TEntity Value { get; set; }
}

View Model:

// IEnumerable<Person>

public class Person
{
    public string Name { get; set; }
}

And using these extension methods:

@Model.ForEachTemplate(@<p>Index: @item.Index Name: @Item.Value.Name</p>)
+5
source

Is there a reason you need to do this?

@foreach(var x in Model.Categories) {
    <li><a href="#">@x.Name</a></li>
}

Above is the same thing, and more idiomatic.

.ForEach() Razor. Razor , , . .ForEach() , , :

'void' 'object'

, :

@foreach (var item in Model.Categories.Select((cat, i) => new { Item = cat, Index = i })) {
   <li><a href="#">@x.Index - @x.Item.Name</a></li>
}

, , Item, Index IEnumerable<T>, yield , .

public static IEnumerable<IndexedItem<T>> WithIndex<T>(this IEnumerable<T> input)
{ 
    int i = 0;
    foreach(T item in input)
        yield return new IndexedItem<T> { Index = i++, Item = item };
}

:

public class IndexedItem<T>
{
    public int Index { get; set; }
    public T Item { get; set; }
}

:

@foreach(var x in Model.Categories.WithIndex()) {
    <li><a href="#">@x.Index - @x.Item.Name</a></li>
}
+7

Source: https://habr.com/ru/post/1793831/


All Articles