c# - asp.net mvc 2 多个局部 View

标签 c# asp.net asp.net-mvc asp.net-mvc-2

我有一个 Controller 可以呈现 3 个不同的 View 。但是对于每个 View ,我也有一个公共(public)部分 (div)。我认为我可以创建一个带有自己的 Controller 的 UserControl 并将该控件包含在我的 View 中(新 Controller 和 View 作为控件)。

我应该如何使用该 UserControl?应该是局部 View 吗? 或者不同的方法 - 我可以在一个页面上有多个局部 View 吗?

最近几天我一直在网上搜索,但没有找到适合我的工作解决方案。我也想使用强类型 View /数据。

干杯

最佳答案

您应该使用分部 View 。然后你打电话<% Html.PartialRender("MyCommonControl", Model); %>在 3-4 View 中呈现公共(public)部分(如菜单或其他内容)。

通过这种方式,您可以强类型化局部 View 并将模型(如上例所示)或相关模型的一部分传递给它。

UserControl 确实是一种 ASP.NET 窗体范例,您应该使用部分 View ,因为它们使用相同的 MVC View 引擎。

更新

如果将 PartialView 放在 /Views/Home 中只有 HomeController 才能访问它你想把它放在 /Views/Common使其可供所有 Controller 访问。

您还应该为控制所需的数据创建一个通用 ViewModel,并将其作为每个 Controller 模型的子组件:

例如:

class CommonSectionViewModel
{
    public string Data { get; set; } // Just Example Data
    public int Count { get; set; }
}

class ProductsModel
{
    public CommonSectionViewModel CommonData { get; set; }
    // Other properties for a products models
}

class CompaniesModel
{
    public CommonSectionViewModel CommonData { get; set; }
    // Other properties for a company model
}

然后在您的 Controller 的 View 中,您可以这样调用局部渲染:

<% Html.PartialView("MyCommonControl", Model.CommonData); %>

注意:您也可以覆盖控件

具有以下文件:

  1. /Views/Common/MyCommonControl.ascx
  2. /Views/Products/MyCommonControl.ascx

当您调用 .RenderPartial("MyCommonControl") 时来自 ProductsController使用#2,从任何其他 Controller ,使用#1。因此,您可以根据需要覆盖某些 Controller 的功能。

关于c# - asp.net mvc 2 多个局部 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2791058/

相关文章:

c# - 未找到站点核心 IComputedIndex 字段类/未运行

c# - [InvalidCastException : Unable to cast object of type 'System.DBNull' to type 'System.String' .]

c# - 在 HttpPost 之后更新模型

asp.net-mvc - asp.net mvc razor 将两项相乘并转换为字符串

ASP.NET MVC - 使用 VS Web 服务器预览 MVC 应用程序中页面更改的最快方法

c# - c#中是否有类似SQL IN语句的比较运算符

c# - 如何在 HTTP 触发器 Azure Function 3.x 中获取操作 IS。附图片

c# - 如何获得屏幕的分辨率?对于 WinRT 应用程序?

c# - UserControl 中的 LinkBut​​ton 回发但不触发 OnClick

c# - 在 ASP.NET MVC C# 中的 Saber 中设置授权 header 和访问数据响应