gpt4 book ai didi

c# - 如何在 ASP.NET MVC 的 View 中使用具体 ViewModel 的 DataAnnotations 而不是接口(interface)?

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

我在我的 MVC webapp 中有一个情况,我正在使用一个接口(interface)的实现作为我的 ViewModel。渲染时, View 使用接口(interface)的 DataAnnotations 而不是具体类。我的 View 模型:

 public interface IAnimalViewModel
{
[Display(Name = "InterfaceVolume")]
int Volume { get; set; }
int NumberOfToes { get; }
}
public class DogViewModel : IAnimalViewModel
{
[Display(Name = "BarkVolume")]
public int Volume { get; set; }

public int NumberOfToes
{
get { return 16; }
}
}
public class CatViewModel : IAnimalViewModel
{
[Display(Name = "MeowVolume")]
public int Volume { get; set; }

public int NumberOfToes
{
get { return 18; }
}
}

我的相关部分观点:

@model IAnimalViewModel
<label asp-for="Volume"></label>
@Model.NumberOfToes

结果:

InterfaceVolume 16

当我将 DogViewModel 传递到我的 View 时,我希望呈现的标签是“BarkVolume”,但它呈现“Volume”,因为使用了 IAnimalViewModel 的 DataAnnotations。 NumberOfToes 显示 16,正如 DogViewModel 对象所预期的那样。

有没有办法让 View 改用类的 DataAnnotations,或者我对 viewModel 的思考方式存在根本性缺陷?

最佳答案

不确定为什么要在 View 中使用界面而不是这个

@model IAnimalViewModel
<label asp-for="Volume"></label>

在 View 中使用 DogViewModel 试试这个

@Html.LabelFor(model => model.Volume)`

现在如果你的模型是 IAnimalViewModel你可能需要

@Html.LabelFor(model => (DogViewModel)model.Volume) 

//尝试将 IAnimalViewModel 转换为 DogViewModel

关于c# - 如何在 ASP.NET MVC 的 View 中使用具体 ViewModel 的 DataAnnotations 而不是接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52633685/

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