2013-01-04 95 views
19

我需要顯示實體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對象'「任何想法?

回答

43

您需要使用這個語法調用渲染方法時:

@{ Html.RenderAction("Items", new { requestId = Model.Id }); } 

@syntax,沒有花括號,預計其獲取呈現頁面返回類型。爲了調用一個從頁面返回void的方法,你必須用大括號包裝這個調用。

請參閱以下鏈接以獲得更深入的解釋。

http://haacked.com/archive/2009/11/18/aspnetmvc2-render-action.aspx

14

用地替代:

@model CAPS.RequestInfo 
...  
@Html.Action("Items", new { requestId = Model.Id }) 

此代碼返回MvcHtmlString。與partialview一起使用並查看結果。不需要{}字符。

+1

+1:同等有效的答案和更適合Razor語法。這需要更多的投票:) –