Search code examples
asp.net-mvc-2viewdatarenderpartial

ASP.NET MVC 2: foreach, RenderPartial, ViewModel


I'm trying to employ a technique that I came across that seems quite clean.

Previously, my Partial had the loop inside of it. I was looping through the mode within the Partial... but then I came across an example where the foreach loop existed in the main page, while the partial was just the meat of the loop.

They accomplished it like so:

<% int index = 1; // iteration
foreach (var item in Model.Deal) { %>

     <% Html.RenderPartial("DealList", item, new ViewDataDictionary {{ "index", index }}); %>

<% i++; // increase the interation
} %>

But in my example, I'm using a ViewModel, and now that I'm in the partial, I can't access "item" like I used to be able to. Instead my only option is Model.Deal ...

What is the point of passsing "item" with the RenderParial helper if I can't access it by saying item.StoreName? Note, both the View and the Partial are strongly typed to the same ViewDataModel.


Solution

  • Inside of the partial "DealList" your model will be whatever item is in the main view. Inside of the partial view, Model.Deal refers to a Deal object inside of item (from the main view).

    This means that your StoreName property will be accessible as Model.StoreName within your partial view.

    As a side note, I put together an extension method to deal with rendering of multiple partial views so as to not require the looping.

    The new method is called RenderPartials:

    public static void RenderPartials(this HtmlHelper helper, string partialViewName, IEnumerable models, string htmlFormat)
            {
                foreach (var view in models.Select(model =&gt; helper.Partial(partialViewName,model)))
                {
                    helper.ViewContext.HttpContext.Response.Output.Write(htmlFormat, view.ToHtmlString());
                }
            }
    

    Using this method you can simple say:

    <% Html.RenderPartials("DealList",Model.Deal); %>
    

    inside your main view, without the loop.

    There's some more information about this here which explains more about the htmlFormat parameter etc.

    Hope this is helpful to you.