Providing partial views in a loop in MVC3

I have a pretty simple script. The model for my view is a list.

Scroll through the list, for example

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

So, I expected to have a number of partial views according to my list.

A partial view has been designed accordingly.

There is no error on the page. It simply does not show any data that should be displayed in partial views.

What is the reason not to show any data?

+4
source share
6 answers

You are lacking @:

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

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

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

and then just define the appropriate editor template ( ~/Views/Shared/EditorTemplates/CustomObject.cshtml ), which will be automatically displayed for each element of your model:

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

Simple and conditional :-)

+9
source

Try: @ Html.RenderPartial ("_ TrackingCustomObject", obj)

0
source

You do not need the Razor @ character:

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

Also make sure your partial view uses the CustomObject object type as the model.

 @model MyProject.Models.CustomObject <h1>Yeah we're in a partial! @Model.SomeProperty </h1> 

To try to expand to the place of the error, try putting some static text inside a PartialView.

 <p>Some text</p> 

If your collection contains 10 items, you should see 10 of these paragraphs. Then, once this is done, focus on displaying some property in each element.

 @model MyProject.Models.CustomObject <p>Some text</p> <p>@Model.SomeProperty</p> 
0
source

When you create an html form using @Html.BeginForm() , you need to wrap the remaining stuf inside a <div> or another container, otherwise the html elements will not be displayed.

Ref.

it will not work

 @using(Html.BeginForm()) { Html.EditorFor(m => m.Name) } 

it will work

 @using(Html.BeginForm()) { <div> @Html.EditorFor(m => m.Name) </div> } 
0
source

A bit at the end of the day, but it worked for me in MVC 4:

  @foreach (var p in @Model.RelatedCards) { Html.RenderPartial("_ThumbPartial", p); } 
0
source

It is too old, but someone can use it.

 @foreach(CustomObject obj in Model) { <text> Html.Partial("_TrackingCustomObject",obj) </text> } 
0
source

All Articles