Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement foreach delegate in razor viewengine?

The following code works for webform view engine.

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

I wrote the above code as below in razor view:

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

But this doesn't work.

Can anyone suggest, Is there any way to achieve this in razor view?

Thanks in advance.

like image 298
learner Avatar asked Jul 10 '26 13:07

learner


1 Answers

Is there any reason you need to do that?

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

Above does the exact same thing, and is more idiomatic.

I can't see a way to output the .ForEach() delegate result using the Razor syntax. Razor expects called methods or invoked properties to return a value, which is then emitted into the view output. Because .ForEach() doesn't return anything, it doesn't know what to do with it:

Cannot explicitly convert type 'void' to 'object'

You can have the iterator index quite tersely like so:

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

If you want to define this as an extension method, instead of an anonymous type, you can create a class to hold the Item, Index pair, and define an extension method on IEnumerable<T> which yields the items in the original enumerable wrapped in this construct.

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 };
}

The class:

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

Usage:

@foreach(var x in Model.Categories.WithIndex()) {
    <li><a href="#">@x.Index - @x.Item.Name</a></li>
}
like image 165
jevakallio Avatar answered Jul 14 '26 05:07

jevakallio



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!