【问题标题】:Displaying a strongly typed partial in a strongly typed view在强类型视图中显示强类型部分
【发布时间】:2012-09-30 03:30:19
【问题描述】:

我不能在强类型视图中呈现强类型部分吗?

我在尝试时收到以下错误:

传入字典的模型项是类型 'System.Data.Linq.Table1[UI.Models.vwProject]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable1[UI.Models.ProjectStatus]'。

我使用 ViewData.Model 填充两个视图

public ActionResult Index()
{
    ViewData.Model = project.vw_Projects;
    return View();
}

public ActionResult ProjectStatus()
{
    ViewData.Model = project.ProjectStatus;
    return View();
}

这是我的观点:

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<IEnumerable<UI.Models.vwProject>>" %>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

    <div>
    <table>
    <tr>
        <th>
            Project
        </th>
        <th>
            Hours
        </th>
    </tr>
    <tr>
        <td>
            <%= Html.Encode(item.ProjectCode) %>
        </td>
        <td>
            <%= Html.Encode(item.ProjectHours) %>
        </td>
    </tr>

<div>
 <%  Html.RenderPartial("ProjectStatus"); %>
</div>

</asp:Content>

这是我的部分:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<IEnumerable<UI.Models.ProjectStatus>>" %>

    <table>
        <tr>
            <th>
                Code
            </th>
            <th>
                Status
            </th>
        </tr>

    <% foreach (var item in Model) { %>

        <tr>
            <td>
                <%= Html.Encode(item.ProjectCode) %>
            </td>
            <td>
                <%= Html.Encode(item.ProjectStatus) %>
            </td>
        </tr>

    <% } %>

    </table>

我对如何在强类型或动态视图中显示强类型/动态部分感到有些困惑。有人可以帮我解决这个问题吗?

【问题讨论】:

  • 不需要将特定对象传入RenderPartial吗?如果你不这样做,它会从调用视图中获取模型。
  • @TLS 是的,我确实需要将特定对象传递给 RenderPartial

标签: c# asp.net-mvc partial-views


【解决方案1】:

是的,你可以。但是,如果您不将模型传递给 RenderPartial,它将使用视图中的模型。 所以,你需要做这样的事情:

Html.RenderPartial("ProjectStatus", new List<ProjectStatus>()); %>

【讨论】:

    【解决方案2】:

    如果你渲染一个局部,它不会影响你的控制器动作,默认情况下使用partent的视图模型渲染视图。

    如果您想调用您的控制器操作ProjectStatus,那么您需要的是RenderAction 方法:

    <%  Html.RenderAction("ProjectStatus"); %>
    

    一篇关于When to use RenderAction vs RenderPartial with ASP.NET MVC的好文章

    【讨论】:

    • 什么时候适合使用动态视图和局部视图?
    • @user793468 在没有给定上下文的情况下通常很难回答您的问题也许您应该问一个不同的问题...我个人从不仅使用强类型的动态视图...我们使用部分当视图可以与手头的模型一起呈现并且不需要在控制器中运行其他代码时。
    猜你喜欢
    • 2013-04-23
    • 2010-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多