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) {
htmlWriter(item);
}
}
(The unused html parameter allows it to be called as an extension method like other HTML helpers)
This code can be called like this:
<ul>
<% Html.ForEach(
Enumerable.Range(1, 10),
item => { %> <li><%= item %></li> <% }
); %>
</ul>
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);
builder.Append(result.ToString());
}
return new HtmlString(builder.ToString());
This method can be called like this:
<ul>
@Html.ForEachSimple(
Enumerable.Range(1, 10),
@<li>@item</li>
);
</ul>
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) {
htmlCreator(item).WriteTo(tw);
}
});
}
This version creates a HelperResult with a delegate that writes each of its items in turn to the TextWriter.
SLaks
415 comments:
«Oldest ‹Older 401 – 415 of 415 Newer› Newest»Maintain the efficiency of your accounting system with the Update Quickbooks Desktop process. Regular updates bring the latest features, security fixes, and performance improvements to your software. If you face any difficulties during the update, call +1-866-500-0076 for expert support. Keeping QuickBooks Desktop updated ensures smooth financial operations, accurate data management, and reliable performance, helping your business stay organized and compliant with the latest accounting standards.
강남구구단 쩜오는 강남 유흥업소 트렌드의 정점에 선 프리미엄 룸싸롱입니다. 화려함을 넘어서 디테일까지 신경 쓴 서비스와 분위기로 이미 많은 단골 고객을 확보하고
Hello, I am Looking the Your Website. This is the Very Good blogging website.
Elevate Your Next Creative Project With Premium Eva Foam Sheet From Fusion Foams. Renowned for Superior Quality, Our Premium Eva Foam Sheet Offers a Perfect Blend of Durability, Flexibility, and a Smooth, Easy-to-cut Surface.
Visit Us -
Premium EVA Foam Sheet India
EVA foam sheet manufacturer
Premium EVA Foam Solutions in India
Very helpful post! The concept of kosher Approved really ensures that products meet strict quality and purity standards. It’s great to see more brands focusing on clean and compliant production. Thanks for explaining it so clearly!
Plan your Air Canada Group Travel effortlessly with Grouptripo. Enjoy customized itineraries, discounted fares, and smooth booking support. Call +1-833-894-5333 for expert assistance and exclusive group deals.
Spirit Airlines Minor PolicyUnited Airlines Minor PolicyAmerican Airlines Minor PolicySouthwest Airlines Minor Policypolítica de selección de asientos de Aerolíneas TurcasSkywest Airlines Minor PolicyDelta Airlines Seat Upgradeklm seat upgradeBreeze Airways Seat upgrade
Your Blog Page Is Very Nice
Ensure Optimal Performance And Player Safety With Professional-grade Kabaddi Tournament Mats. Designed For High-intensity Raids And Swift Defensive Moves, These Mats Provide The Perfect Surface For Competitive Play. For Organizers Seeking Durability And Superior Shock Absorption, Gravolite Is The Best Choice.
Visit Us -
Kabaddi Mats Supplier Delhi
Premium Kabaddi Mats Supplier, Manufacturer & Wholesaler in India
Kabaddi Mats Exporter India
A free funded forex account is a great way for traders to start without taking on financial risk. Winprofx provides this opportunity by offering structured funding programs that allow traders to prove their skills while accessing real trading capital.
Appreciate the well-organized and thoughtful presentation.
Electrical Connectors
Hello, I am Looking the Your Website. This is the Very Good blogging website.
Neoprene Foam Manufacturers In India Are An Essential Part Of The Industrial Supply Chain, Serving The Needs Of Various Sectors Such As Automotive, Sports, And Marine. When Finding A Reliable Neoprene Foam Manufacturer In India, It's Important To Partner With A Company That Ensures Consistent Quality, Durability, And Customization. Visit Us - Fusion Foams
Hello, I am Looking the Your Website. This is the Very Good blogging website.
For Schools, Sports Academies, And Professional Leagues Looking For A Reliable Kabaddi Mat Supplier, Their Focus Is On Safety, Durability, And True Sport-specific Performance. As A Trusted Kabaddi Mat Supplier, Gravolite Creates Its Solutions To Meet These Demands. Visit Us - Kabaddi League Mats
I've always struggled with managing multiple deadlines, so I eventually turned to Native Assignment Help just to survive the workload. I didnt expect it to help this much, but it honestly did. They helped me get my workload under control and, for the first time, actually understand what each assignment was asking for. Later, when my unilever coursework started getting tougher, I tried unilever leadership style, especially understanding how Unilevers leaders combine transformational vision, ethical decision-making, collaborative culture, and strategic direction to guide teams and drive global success, and it honestly became a complete lifesaver. Instead of feeling overwhelmed by criteria, units, and endless task requirements, I finally had someone guiding me through everything in a way that actually made sense.
Hello, I am Looking the Your Website. This is the Very Good blogging website.
As a premier supplier of Kabaddi Marking Tape, we understand the critical need for precision, durability, and safety in every match. That’s why we exclusively offer Gravolite tournament-grade solutions.
Hello, I am Looking the Your Website. This is the Very Good blogging website.
For Top-quality EPDM Foam Manufacturers In Delhi, Fusion Foams Is Your First Choice. We Specialize In Closed-cell EPDM foam, Which Is Renowned For Its Excellent Weather Resistance, Sealing Properties, And Durability. Get Direction
Visit Us -
EVA Foam
SBR Foam
PE Foam
Hey, this vacation was about getting back together with loved ones after being apart for years, not simply about flying. I felt confident enough to finally purchase my ticket after learning Which airlines provide in-flight oxygen or portable oxygen concentrators (POCs). I was treated with such kindness on board. I experienced emotional calm, stability, and relaxation. Rather than worrying, I imagined hugging my family once again while gazing out the window. For me, that comfort was everything.
Post a Comment