asp.net-mvc-4 - 如何从不同的模型/ Controller 渲染局部 View ?

标签 asp.net-mvc-4 partial-views

我有以下名为 _Categories 的部分 View 位于 ~/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 中有以下索引 View :

@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”的“模型”。

最佳答案

我为我的 partialview 创建了 viewmodel,然后传递它的数据。例如: 我的 View 模型

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

局部 View

@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>
----

关于asp.net-mvc-4 - 如何从不同的模型/ Controller 渲染局部 View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17626811/

相关文章:

c# - 部分 View 刷新和脚本不起作用

asp.net-mvc-4 - ASP.NET Web API 架构建议/反馈

c# - 如何处理 Multi-Tenancy ASP MVC 站点的路径设置

c# - 使用安装在 ASP.NET MVC 4 应用程序中的 Elmah 进行异常处理

rest - ASP.NET Web API身份验证选项

c# - 在模态弹出窗口中显示局部 View

javascript - Angular 创建动态导航栏

c# - 更改所有页面的文本方向

ruby-on-rails - Ruby on Rails——Heroku : Issue with votes button only in production

ruby-on-rails - 如何创建仅包含部分的 4x4 网格?