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
.
225 comments:
«Oldest ‹Older 201 – 225 of 225 Newer› Newest»custom valet uniforms from AMM Hotel Couture, your valet team can look professional, elegant, and reliable. Our stylish valet outfits enhance your brand image while providing comfort and functionality for your team.
One of the reasons Swadeshi Button is so highly regarded among zinc casting button manufacturers is its commitment to using only the highest-quality materials. The zinc alloy used in production is carefully selected to ensure its strength and longevity, making the buttons ideal for use in challenging environments. This focus on quality control extends to every production stage, from design to casting, ensuring that the end product exceeds expectations.
CS Enterprises proudly supplies Burstwick Community Primary School Uniforms, providing families in the UK with high-quality and affordable options. School uniforms foster a sense of belonging, equality, and pride among students, and we ensure every child has access to comfortable and durable attire for their educational journey.
students need in-depth explanations, practice tests, or tips for improving exam skills, Yellow Bird Publications offers the best Reference Book for Class 10 to help them succeed.
One of the biggest concerns when choosing a school uniform is how easily it can be maintained. Stich Cart has ensured that Noor Al Islam School Dress is easy to care for. The fabric is machine washable and retains its color and texture even after multiple washes, making it a practical choice for busy families.
Money Hub UAE is committed to providing seamless and reliable personal loan solutions. Their experts work closely with clients to assess their needs and recommend the most suitable loan packages. They understand that life can present unpredictable situations, and a personal loan in UAE may be the key to securing your financial well-being during such times.
Swadeshi Button offers a diverse range of Sheesham wood buttons; each handcrafted with precision. Their commitment to delivering high-quality products has earned them a trusted reputation in the fashion industry. Below are some of the key reasons why Swadeshi Button is the preferred choice for Sheesham Wood Buttons suppliers.
Abhinaari is dedicated to helping women achieve their full potential by providing them with education, skills, and leadership opportunities. Through its programs, Abhinaari is making a lasting impact on women’s lives, empowering them to break barriers, create sustainable futures, and lead confidently. By continuing to support and uplift women, Abhinaari is helping build a more inclusive and equal society for all.
One of the standout features of Pentoink acrylic paint is its smooth consistency. It glides effortlessly onto various surfaces, allowing smooth strokes, seamless blending, and easy layering. Artists can create everything from fine details to textured surfaces with ease. Its user-friendly nature makes Pentoink perfect for beginners, while its professional-grade quality satisfies even the most experienced artists.
The Lab Manual for Class 10 by Yellow Bird Publications is an invaluable resource for students aiming to master practical science concepts. With well-structured experiments, step-by-step instructions, and comprehensive theoretical explanations, this manual provides a holistic learning experience.
CS Enterprises takes pride in providing Burton Pidsea Primary School Uniforms that are high-quality, durable, and comfortable. Our uniforms help students feel confident and ready to face the school day. We commit to delivering products that meet the highest standards of quality and design, allowing students to proudly represent their school.
One of the key factors to consider when applying for a personal loan in UAE is the interest rate. Interest rates can differ across financial institutions and are often influenced by your credit score, income level, and the loan term. Money Hub UAE ensures that you have access to competitive rates and helps you compare offers from various banks and financial institutions in the UAE. This enables you to make an informed decision that best suits your financial situation.
AMM Hotel Couture, we offer customization options to ensure your special events uniforms reflect the personality and theme of your event.
CS Enterprises, we understand the vital role that Burstwick Community Primary School Uniforms play in shaping the school experience for children.
The Reference Book for Class 10 by Yellow Bird Publications is designed to be that guiding resource, offering students a comprehensive, user-friendly tool to prepare for their exams effectively
We also offer construction loans provider UK services for those looking to build their dream home. If you plan to construct your property from the ground up, our construction loan provider services in the UK ensure you have the right financing to support your project. These loans are designed to cover construction costs with flexible repayment terms that work for you.
Our Licenses and Registrations Lawyer services cover a wide range of needs for both new and established businesses. Here’s what we offer
A well-made school uniform reflects a student’s discipline and a school’s reputation. Stich Cart ensures that Green Hills International School uniforms are designed with quality, durability, and style in mind. Choose Stich Cart for the best in school uniforms!
Great post on using foreach in Razor! It’s such a powerful feature. By the way, if you're in Coimbatore and running a food business, don't forget about FSSAI Registration in Coimbatore for proper certification.
Along with securing a mortgage, it's vital to protect your investment and ensure that your mortgage payments are covered in unforeseen circumstances. Money Hub, as a trusted Insurance for Mortgage Loans Provider, understands the importance of safeguarding your home mortgage UK, so they offer comprehensive insurance for mortgage loans.
Great read! It's a super helpful method for iterating through collections in views. The example code you shared made it really easy to understand how to use it effectively. Looking forward to seeing more tips like this. Keep up the great work!
new jersey sex crimes lawyer
Porcelain Tile Manufacturers are a crucial consideration when selecting high-quality tiles for your home or commercial space
An Insolvency Lawyer is a legal professional specializing in insolvency and bankruptcy laws.
The design of the uniforms is just as important as the fabric. We at Stich Cart believe in providing styles that promote a sense of unity and pride among students. The Green Hills International School uniforms feature a modern and clean design, with well-tailored fits that allow for ease of movement while maintaining a polished look. Whether it’s a polo shirt, trousers, or a skirt, every piece in the collection complements the professional yet welcoming atmosphere of the school.
The Ajyal School Dress for Student by Stich Cart is an excellent investment for parents looking for quality, comfort, and style in school uniforms. Its thoughtful plan and durable materials ensure students are well-equipped to tackle their academic challenges while looking their best. Choose Stich Cart for a uniform that genuinely meets the needs of Ajyal National School students.
Post a Comment