我正在尝试在 ASP.NET MVC 应用程序中构建通用 GridView 。
让我用一些代码来解释:
public interface ITrustGrid<T>
{
IPagedList<T> Elements { get; set; }
IList<IColumn<T>> Columns { get; set; }
IList<string> Headers { get; }
}
这是一个类的接口(interface),允许我在我的 Controller 中设置列和表达式。
我将实现传递给这样的分部 View :
<% Html.RenderPartial("SimpleTrustGridViewer", ViewData["employeeGrid"] as TrustGrid<EmployeeInfoDTO>); %>
问题是我不知道如何制作呈现通用网格的局部 View 。
换句话说,我想把这个:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<ITrustGrid<EmployeeInfoDTO>>" %>
像这样:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<ITrustGrid<T>>" %>
=> 如何以最简单的方式使我的分部 View 通用?
编辑:
我通过使用具有返回非通用 TrustGrid 的公共(public) TrustGrid GetTrustGrid() 方法的 TrustGridBuilder 解决了这个问题。 TrustGrid 包含字符串而不是 linq 内容。因此,我在 GetTrustGrid() 方法中执行 linq,并将字符串放入 TrustGrid 对象中。
感谢大家帮助我走上正轨。
最佳答案
您可以使您将传递给此局部 View 的所有模型类型都继承自基类/接口(interface),该基类/接口(interface)建立了此局部 View 将使用的基本行为,并接受该类/接口(interface)类型的任何对象,或者只是让 View 接受任何类型的对象,然后使用反射来使您的部分 View 行为基于此。
示例:
public interface IDisplayModel
{
string DisplayText{get;set;}
string ImageUrl{get;set;}
string AltText{get;set;}
}
public interface ITrustGrid<T> where T : IDisplayModel
{
IPagedList<T> Elements { get; set; }
IList<IColumn<T>> Columns { get; set; }
IList<string> Headers { get; }
}
<%@ Control Language="C#"
Inherits="System.Web.Mvc.ViewUserControl<ITrustGrid<IDisplayModel>>" %>
当然,您的 IDisplayModel
会根据您想要的行为而有所不同。然后,这将允许您将任何内容传递给实现此基本接口(interface)的此部分以建立一般行为。
关于c# - 通用局部 View : how to set a generic class as model?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/875085/