Tags: , , , | Categories: ASP.Net, C#, MVC, Razor Posted by Admin on 5/4/2011 9:06 AM | Comments (5)

To define a method within a razor (cshtml) file. Very useful for recursive rendering of data trees.

@model ListOfItemsViewModel

@if (Model.Items.Any())
{
    <ul>
    @foreach(var item in Model.Items)
    {
        @RenderItem(item);
    }
    </ul>
}

@helper RenderItem(Item item)
{
    @MvcHtmlString.Create(string.Format"<li>{0}", item.Name)
    if (item.Children.Any())
    {
        @MvcHtmlString.Create("<ul>")
        foreach(var childItem in itemChildren)
        {
            @RenderItem(childItem);
        }
        @MvcHtmlString.Create("</ul>")
    }
    @MvcHtmlString.Create("</li>");
}

Comments (5) -

Letters from Nowhere 2 United States on 5/9/2011 8:22 AM Thank you for the simply informative posting, informative tips like this convinced your visitors always to come and read again and share this to the other people.
Fazillah United States on 5/14/2011 1:48 AM artikel memuaskan hati, rencana manfaat kepada sesiapa pun.
Valentine Winney United States on 6/2/2011 1:14 PM great post! blog favorited (:
Tana United States on 1/1/2012 6:16 PM Thanks for sharing. I came here from google search.
Brendon United States on 4/26/2012 12:04 PM This is exactly the content I needed. Thank you for writing this publish.

Add comment




  Country flag
biuquote
  • Comment
  • Preview
Loading