Tarik
Tarik

Reputation: 81771

Passing HTML Elements in as Func<> in Razor View Engine

I was checking out some sample codes and I saw something like this:

@(Html.DataList<ProductOverviewModel>(Model, 4,
      @<div class="item-box">
        <div class="item">
          <div class="picture">
            <a href="@Url.RouteUrl("Product", new { productId = item.Id, SeName = item.SeName })" title="@item.DefaultPictureModel.Title">
              <img alt="@item.DefaultPictureModel.AlternateText" src="@item.DefaultPictureModel.ImageUrl" title="@item.DefaultPictureModel.Title" /></a>
          </div>
          <div class="product-title">
            <a href="@Url.RouteUrl("Product", new { productId = item.Id, SeName = item.SeName })" title="@item.DefaultPictureModel.Title">
              @item.Name</a>
          </div>
        </div>
      </div>
))

so basically there is a DataList helper method that's signature is this:

public static IHtmlString DataList<T>(this HtmlHelper helper, IEnumerable<T> items, int columns, Func<T, HelperResult> template) where T : class

and they passed the following part as Func<T,HelperResult> template and it works perfectly:

  @<div class="item-box">
    <div class="item">
      <div class="picture">
        <a href="@Url.RouteUrl("Product", new { productId = item.Id, SeName = item.SeName })" title="@item.DefaultPictureModel.Title">
          <img alt="@item.DefaultPictureModel.AlternateText" src="@item.DefaultPictureModel.ImageUrl" title="@item.DefaultPictureModel.Title" /></a>
      </div>
      <div class="product-title">
        <a href="@Url.RouteUrl("Product", new { productId = item.Id, SeName = item.SeName })" title="@item.DefaultPictureModel.Title">
          @item.Name</a>
      </div>
    </div>
  </div>

What rule is this and how is it possible?

Upvotes: 4

Views: 585

Answers (1)

Travis J
Travis J

Reputation: 82297

You have all the words in there already :) What you are looking at is a "Templated Razor Delegate". I could explain it, but Phil Haack does it much better here: http://haacked.com/archive/2011/02/27/templated-razor-delegates.aspx

Upvotes: 3

Related Questions