C# 如何在ASP.NET MVC的视图中使用具体ViewModel的DataAnnotation代替接口?
在我的MVC webapp中,我使用一个接口的实现作为我的ViewModel。呈现时,视图使用接口的DataAnnotation,而不是具体的类。 我的viewModels:C# 如何在ASP.NET MVC的视图中使用具体ViewModel的DataAnnotation代替接口?,c#,asp.net-core-mvc,C#,Asp.net Core Mvc,在我的MVC webapp中,我使用一个接口的实现作为我的ViewModel。呈现时,视图使用接口的DataAnnotation,而不是具体的类。 我的viewModels: public interface IAnimalViewModel { [Display(Name = "InterfaceVolume")] int Volume { get; set; } int NumberOfToes { get; } } public class DogViewMode
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
@model IAnimalViewModel
@模型编号
结果:
界面演化图16
当我将DogViewModel
传递给我的视图时,我希望呈现的标签是“BarkVolume”,但它呈现“Volume”,因为使用的是IAnimalViewModel的数据注释。NumberOfToes显示16,与DogViewModel
对象的预期一样
有没有办法让视图使用类的DataAnnotation,或者我对viewModels的思考方式有根本性的缺陷?不确定为什么要在视图中使用接口 而不是这个
@model IAnimalViewModel
<label asp-for="Volume"></label>
现在,如果您的模型是IAnimalViewModel
你可能需要
@Html.LabelFor(model => (DogViewModel)model.Volume)
//试图将IAnimalViewModel转换为DogViewModel的做法并没有缺陷,只是因为模型是一个IAnimalViewModel,所以框架将在这里寻找注释。如果需要具体的注释,则需要将其强制转换为具体类,但注释没有那么干净:(第二个链接(第一个问题)推荐。简短的回答是你不能-你的视图有
@model IAnimalViewModel
,因此它将使用IAnimalViewModel
的元数据。谢谢你的回答!我使用界面是因为我试图只使用一个视图。虽然类型转换工作正常,但我不能始终确定所讨论的模型是DogV那么@Html.LabelFor(model=>model.Volume)`应该可以工作了,我很确定model=>(DogViewModel)model.Volume将以类似的方式中断模型生成。
@Html.LabelFor(model => model.Volume)`