Html.ForEach in Razor

Many people write ForEach extension methods for MVC WebForms views, which take a sequence and a delegate to turn each item in the sequence into HTML.

For example:

public static void ForEach<T>(this HtmlHelper html,
                              IEnumerable<T> set, 
                              Action<T> htmlWriter) {
    foreach (var item in set) {

(The unused html parameter allows it to be called as an extension method like other HTML helpers)

This code can be called like this:

    <% Html.ForEach(
            Enumerable.Range(1, 10),
            item => { %> <li><%= item %></li> <% }
    ); %>

This code creates a lambda expression that writes markup to the page’s response stream by ending the code block inside the lambda body. Neither the lambda expression nor the ForEach helper itself return anything; they both write directly to the response.

The List<T>.ForEach method can be called exactly the same way.

In Razor views, this method cannot easily be called directly, since Razor pages cannot put markup inside of expressions.  You can use a workaround by creating an inline helper and calling it immediately, but it would be better to rewrite the ForEach method to take an inline helper directly.

The naïve way to do that is like this:

public static IHtmlString ForEachSimple<T>(
        this HtmlHelper html,
        IEnumerable<T> set,
        Func<T, HelperResult> htmlCreator
    ) {
    return new HtmlString(String.Concat(set.Select(htmlCreator)));

The htmlCreator delegate, which can be passed as an inline helper, returns a HelperResult object containing the markup generated for an item.

This code uses LINQ to call htmlCreator on each item in the set (the Select call), then calls String.Concat to combine them all into one giant string.  (String.Concat will call ToString on each HelperResult, which will return the generated markup)  We could also call String.Join to put a separator, such as a newline, between every two items.

Finally, it returns an HtmlString to prevent Razor from escaping the returned HTML.

It’s equivalent to the following code using a StringBuilder (this is what String.Concat does internally)

var builder = new StringBuilder();
foreach (var item in set) {
    HelperResult result = htmlCreator(item);
return new HtmlString(builder.ToString());

This method can be called like this:

        Enumerable.Range(1, 10),

The problem with this approach is that it combines all of the content into a giant string.  If there are a large number of items, or if each item will have a large amount of markup, this can become (a little bit) slow.  It would be better to write each item directly to the caller’s response stream, without assembling any giant strings.  This is where HelperResult comes in.

The HelperResult class allows its caller to pass a TextWriter to the WriteTo method, and the helper delegate will write directly to this TextWriter.  I can take advantage of this to write a ForEach extension that doesn’t build any strings, by returning a HelperResult instead of a regular IHtmlString.

public static HelperResult ForEachFast<T>(
        this HtmlHelper html,
        IEnumerable<T> set,
        Func<T, HelperResult> htmlCreator
    ) {
    return new HelperResult(tw => {
        foreach (var item in set) {
This version creates a HelperResult with a delegate that writes each of its items in turn to the TextWriter.


Really good to know things like that

look here

The above article is nice and interesting, thank you willing to share! Greetings success of admin Percetakan Murah Rawamangun Jakarta Timur wish you deign to visit my website, thank you :)

You may want to check out this website for some tips on how to write great looking essay. Good luck with that

Excellent erudition Providing by your Article, thank you for taking the time to share with us such a nice article. Amazing insight you have on this, it's nice to find a website that details so much information about different artists. Kindly visit the LiveWebTutors website we providing the best online assignment help services in Australia.

For More Info: Law Assignment Help

Thank you for this information, it is very useful for all. Get the best My Assignment Help Services at the cheapest price. Myassignmenthelpau provides the best organizational culture Assignment help Sydney. Therefore, to avail of our assignment help offering no plagiarism, Free Turnitin, Partial Payment, Unlimited Revisions, etc. you'll contact our team of highly professional, experienced, Ph.D. experts to avail the discounted services!

mr jatt Mp3 New Punjabi Song,Single Tracks Latest song download also Listen Latest Music Albums Online in High Quality at
mr jatt

Finding the best Help with Medical Assignment is not easy unless one is keen to establish a professional medical assignment help & medical homework help online.

Online religion research paper writing services are very difficult to complete and many students are always searching for Religion Research Paper Services companies to help them complete their custom religion essay writing services.

Those seeking education assignment writing services have an advantage of hiring online education assignment writers who are familiar with research papers on teaching & education for their Online Education Assignment Help.

Online law research paper help services are very common nowadays since there are very many students seeking Law Research Writing Services and law essay writing services.

Hi…this is abhinav here, the few months I am visiting and following you. What I really like about you is that your writing style. Please keep making such as information for us. Top CA Firm in India – AKGVG, Top CA in India. - McAfee LiveSafe 2020 Crack: It is powerful and all-in-one security software. Furthermore, it offers all kinds of protection for digital systems such as Mac OS and Windows PC. So, it prevents your PC from many attackers as well as online Moreover, it assists to secure smart-phone and tabs from virus attacks. Redeem and activate McAfee using the activation code on

Download and install McAfee from McAfee. It is an industry-leading antivirus program that powers small businesses to large corporations throughout the world. You can visit Mcfaee and download, install and activate your preferred product from the list. Returning users can visit to redeem their 25-digit activation code and start with their download right away.

This QB database server error usually occurs when you try to install QuickBooks update or while trying to upgrade it to a newer version and the Windows firewall is still not updated, this causes the firewall to detect QBDBMgrN service as an unknown service, and it blocks its access to the internet. This error also occurs when you are using Quickbooks in multi-user mode.
Quickbooks database server error

Everyone should know about the vastu because it makes you life and future better, there are

some principles which everyone to need to follow it, the followers of vastu shastra are

prosperous and safe.

Vastu Consultant
Vastu Experts
Vastu Consultants
Southern Hemisphere Vastu
Vastu in Southern Hemisphere
Vastu for Southern Hemisphere

Amazing and infromative post, checkout this as well:-
online environmental science tutor

If you feel like you have lost the zeal and intimacy of your sexual life then a reliable sexologist in Delhi is something that you certainly need. He has registered himself in the list of the top reputed sexologist. You have got it here! He is an honorable name in the industry of sexologist treatment and best sexologist in Delhi or top sexologist in Faridabad.

Post a Comment