我需要顯示實體Request
的一些子對象(Items
)。除了請求之外,我發現最好傳入包含比原始請求實體更多信息的視圖。這個視圖我稱爲RequestInfo
,它也包含原始請求Id
。在MVC4問題中使用RenderAction(actionname,values)
然後在MVC查看我所做的:
@model CAPS.RequestInfo
...
@Html.RenderAction("Items", new { requestId = Model.Id })
渲染:
public PartialViewResult Items(int requestId)
{
using (var db = new DbContext())
{
var items = db.Items.Where(x => x.Request.Id == requestId);
return PartialView("_Items", items);
}
}
這將顯示一個泛型列表:
@model IEnumerable<CAPS.Item>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th>
@Html.DisplayNameFor(model => model.Code)
</th>
<th>
@Html.DisplayNameFor(model => model.Description)
</th>
<th>
@Html.DisplayNameFor(model => model.Qty)
</th>
<th>
@Html.DisplayNameFor(model => model.Value)
</th>
<th>
@Html.DisplayNameFor(model => model.Type)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Code)
</td>
<td>
@Html.DisplayFor(modelItem => item.Description)
</td>
<td>
@Html.DisplayFor(modelItem => item.Qty)
</td>
<td>
@Html.DisplayFor(modelItem => item.Value)
</td>
<td>
@Html.DisplayFor(modelItem => item.Type)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.Id }) |
@Html.ActionLink("Details", "Details", new { id=item.Id }) |
@Html.ActionLink("Delete", "Delete", new { id=item.Id })
</td>
</tr>
}
</table>
但我得到一個編譯器錯誤在RenderAction
行「不能將類型'void'隱含轉換爲'o對象'「任何想法?
+1:同等有效的答案和更適合Razor語法。這需要更多的投票:) –