Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rendering Partial Views in a Loop in MVC3

I have a pretty simple scenario, Model for my view is a List.

Loop through List like

@foreach(CustomObject obj in Model)
{
Html.Partial("_TrackingCustomObject",obj)
}

So i was expecting to have number of partial views according to my list.

Partial View has been developed accordingly.

There is no error on page. It just does not show any data that is supposed to display by partial views.

What is the reason of not showing any data?

like image 220
manav inder Avatar asked Jul 13 '12 17:07

manav inder


1 Answers

You are missing an @:

@foreach(CustomObject obj in Model)
{
    @Html.Partial("_TrackingCustomObject", obj)
}

But why writing foreach loops when you can use editor/display templates? Like this:

@model IEnumerable<CustomObject>
@Html.EditorForModel()

and then simply define the corresponding editor template (~/Views/Shared/EditorTemplates/CustomObject.cshtml) that will automatically be rendered for each element of your model:

@model CustomObject
<div>
    @Html.EditorFor(x => x.Foo)
</div>

Simple and conventional :-)

like image 76
Darin Dimitrov Avatar answered Oct 04 '22 02:10

Darin Dimitrov