2013-07-13 81 views
2

我叫_Categories以下的局部視圖居住在〜/查看/分類/ _Categories:如何渲染來自不同模型/控制器的局部視圖?

@model IEnumerable<MyBlogSite.Models.BlogPostCategory> 

<ul> 
@foreach (var item in Model) 
{ 
    <li>@Html.DisplayFor(modelItem => item.Name)</li> 
} 
</ul> 

我在〜/查看/博客/ Index.cshtml以下索引視圖:

@model IEnumerable<MyBlogSite.Models.BlogPost> 

@{ 
    ViewBag.Title = "Index"; 
} 

@Html.RenderPartial("~/Views/Category/_Categories.cshtml", ----); 

<p> 
    @Html.ActionLink("New Blog Post", "Create") 
</p> 
<table> 
<tr> 
    <th> 
     @Html.DisplayNameFor(model => model.Title) 
    </th>  
    ... 

在破折號(----)的空間中,我一直在試圖弄清楚如何傳遞模型。我不能使用Model.BlogPostCategory,因爲它只接受Model.BlogPost。根據我在這裏看到的幾個帖子,我也嘗試過使用小寫「m」的「模型」。

回答

5

我創建viewmodel爲我的partialview,然後傳遞其數據。例如: 我的視圖模型

public class CompanyCreateViewModel 
{ 
    public Company Company { get; set; } 
    public IList<CompanyContact> CompanyContacts { get; set; } 
    public IQueryable<ContactType> ContactTypes { get; set; } 
} 

partialview

@model Invoice.Model.HelperClasses.CompanyCreateViewModel 
--- 
<div class="editor-field"> 
     @Html.TextBoxFor(model => model.Company.FullName) 
     @Html.ValidationMessageFor(model => model.Company.FullName) 
     @Html.TextBoxFor(model => model.Company.ShortName) 
     @Html.ValidationMessageFor(model => model.Company.ShortName) 
     @Html.TextBoxFor(model => model.Company.TIN) 
     @Html.ValidationMessageFor(model => model.Company.TIN) 
    </div> 
    <div class="editor-field"> 
     @Html.TextBoxFor(model => model.Company.Address.Country) 
     @Html.TextBoxFor(model => model.Company.Address.City) 
     @Html.TextBoxFor(model => model.Company.Address.Street) 
    </div>  
    --- 

,並呼籲partialview查看

@model Invoice.Model.HelperClasses.CompanyViewModel 
--- 
<div id="CompanyCreateModal" class="modal hide fade"> 
    @{Html.RenderPartial("CompanyParts/CompanyCreateModal", new Invoice.Model.HelperClasses.CompanyCreateViewModel() { ContactTypes = Model.ContactTypes }); 
    } 
</div> 
---- 
相關問題