如何从不同的模型/控制器渲染局部视图? [英] How to render a partial view from a different model/controller?
问题描述
我在〜/Views/Category/_Categories中有以下名为_Categories的局部视图:
I have the following partial view called _Categories residing in ~/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中具有以下索引视图:
I have the following Index view at ~/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"作为模型".
In the space of the dashes (----) above is where I have been trying to figure out how to pass the model in. I cannot use Model.BlogPostCategory because it only accepts Model.BlogPost. I have also tried "model" with a lower-case "m" as per a couple of posts that I saw here.
推荐答案
我为我的 partialview 创建 viewmodel ,然后传递其数据.例如: 我的视图模型
I create viewmodel for my partialview, then pass its data. For example: my 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>
----
这篇关于如何从不同的模型/控制器渲染局部视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!