我必须创建共享部分 View Partial1,它将在其他屏幕上使用。 因此,我可以创建接口(interface) IPartialModel1,而不是为共享组件创建特定模型 PartialModel1。
然后其他屏幕可以实现 IPartialModel1 就像
BigScreenModel1:IPartialModel1
BigScreenModel2:IPartialModel1
所以在 BigScreen.cshtml 中我可以使用
@Html.Partial("Partial",BigScreenModel1)
以及 BigScreen2.cshtml
@Html.Partial("Partial",BigScreenModel2)
这是好的做法吗?
最佳答案
虽然这种方法可行,但我遇到的问题是,您将部分的 View 模型与包含页面的 View 模型联系起来。
更好的方法是将部分 View 模型作为页面 View 模型的成员,如下所示:
public class BigScreenModel1
{
public PartialViewModel OtherViewModel { get; set; }
}
public class BigScreenModel2
{
public PartialViewModel OtherViewModel { get; set; }
}
然后当然是:
@Html.Partial("Partial", Model.OtherViewModel)
在两个页面上。这将 View 模型彼此解耦。
关于c# - 在共享组件中使用接口(interface)作为模型是个好方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13728237/