我有以下部分视图,名为_Categories驻留在〜/ Views / Category / _Categories中:
@model IEnumerable<MyBlogSite.Models.BlogPostCategory>
<ul>
@foreach (var item in Model)
{
<li>@Html.DisplayFor(modelItem => item.Name)</li>
}
</ul>
我在〜/ Views / Blog / 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”的“模型”。
答案 0 :(得分:5)
我为 partialview 创建 viewmodel ,然后传递其数据。例如: 我的viewmodel
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>
----