gpt4 book ai didi

c# - 如何将接口(interface)的具体实现传递到接受泛型接口(interface)的 MVC 局部 View 中?

转载 作者:太空宇宙 更新时间:2023-11-03 14:45:51 26 4
gpt4 key购买 nike

_PaginationPartialView.cshtml:

@model IPagedListViewModel<object>
<p>PartialTest</p>

Index.cshtml:

@model PagedDocumentList
Html.RenderPartial("_PaginationPartialView", Model);

IPagedListViewModel.cs & PagedDocumentList.cs:

 public class PagedDocumentList : IPagedListViewModel<DocumentEntity>
{
public PagedDocumentList()
{
ListOfItems = new List<DocumentEntity>();
}

public int NumberOfPagesAvailable { get; set; }
public int CurrentPageIndex { get; set; }
public int PageSize { get; set; }
public List<DocumentEntity> ListOfItems { get; set; }
}

public interface IPagedListViewModel<T>
{
int NumberOfPagesAvailable { get; set; }
int CurrentPageIndex { get; set; }
int PageSize { get; set; }
List<T> ListOfItems { get; set; }
}

我正在尝试将具体类型传递到局部 View 中,但出现以下错误:

The model item passed into the dictionary is of type 'PagedDocumentList', but this dictionary requires a model item of type 'IPagedListViewModel`1[System.Object]'.

由于 PagedDocumentList 实现了 IPagedListViewModel,我希望我能够将具体实例传递到局部 View 中,然后读取 对象部分 View 中的属性。如何使用接受通用类型接口(interface)的单个​​分部 View ?

我不喜欢的解决方法:

如果我更新部分以使用以下模型:

@model IPagedListViewModel<DocumentEntity>

然后部分按预期呈现。但我不想输入我的部分 - 我想用不同的类型重用它。

我还可以按如下方式更改 PagedDocumentList:

public class PagedDocumentList
{
public PagedDocumentList()
{
ListOfItems = new List<DocumentEntity>();
}

public PaginationDetails PaginationDetails { get; set; }
public List<DocumentEntity> ListOfItems { get; set; }
}

public class PaginationDetails
{
public int NumberOfPagesAvailable { get; set; }
public int CurrentPageIndex { get; set; }
public int PageSize { get; set; }
}

但是接口(interface)只会强制存在一个具体类型,而不是在我的部分 View 中充当签名。我更喜欢让部分 View 接受一个通用接口(interface),这样我就不需要创建一个新类“只是为了让它工作”。 PaginationDetails 实际上并不是一个 - 它是某些类可能实现 的属性集合。

最佳答案

希望我正确理解了您的问题。 (请在投票前给我理由,哈哈)。我会做一些改变。首先,您的界面更像是一个抽象类。接口(interface)(以我的理解)有方法(动词)。方法有实现。

 public abstract PagedListViewModel
{
int NumberOfPagesAvailable { get; set; }
int CurrentPageIndex { get; set; }
int PageSize { get; set; }
}

您的 View 需要是强类型的(比如特定类型而不是通用类型)。因此,您的子类将在这里使用。

@model PagedDocumentList
// rest of the code

现在,您的局部 View :

@model PagedListViewModel
@Html.EditorFor(o=>o.NumberOfPagesAvailable)
@Html.EditorFor(o=>o.PageSize)

关于c# - 如何将接口(interface)的具体实现传递到接受泛型接口(interface)的 MVC 局部 View 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54246126/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com