Rendering Partial Views in a Loop in MVC3

2019-06-25 08:52发布

问题:

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?

回答1:

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 :-)



回答2:

Try : @Html.RenderPartial("_TrackingCustomObject",obj)



回答3:

You're missing the Razor symbol @:

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

Also make sure your partial view is using the object type CustomObject as the Model.

@model MyProject.Models.CustomObject

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

To try and drill down to where the error is, try placing some static text inside the PartialView.

<p>Some text</p>

If your collection has 10 items, then you should see 10 of these paragraphs. Next once this works, focus on displaying some property in each item.

@model MyProject.Models.CustomObject

<p>Some text</p>
<p>@Model.SomeProperty</p>


回答4:

When you are creating html form using @Html.BeginForm() you have to wrap the remaining stuf inside a <div> or other container else the html elements won't get rendered.

Ex.

this won't work

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

this will work

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


回答5:

Bit late in the day, but this worked for me in MVC 4:

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


回答6:

This is too old but someone can use it.

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