为什么此ASP.NET Core DataAnnotation在ViewModel中有效,而在Model中不起作用 [英] Why this ASP.NET Core DataAnnotation works in ViewModel but not in Model alone

查看:124
本文介绍了为什么此ASP.NET Core DataAnnotation在ViewModel中有效,而在Model中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的一个ASP.NET Core应用中,一个 View 使用的是ViewModel。 ViewModel的基础模型具有属性 StartDate 。该模型在 StartDate 上具有 DataAnnotion ,但是我没有使用相同的 DataAnnotation ViewModel StartDate 上,因为我认为如果 DataAnnotation 在模型中,然后汇总到您的 viewmodels 中。因此,以下 View 应该将 StartDate 仅显示为日期。但是视图显示的是 StartDate 作为日期和时间,例如 2015/9/30上午12:00:00 。另一方面,如果我在<$ c中的 StartDate 属性上使用DataAnnotation [DataType(DataType.Date)] $ c> ViewModel 以及 View 正确地将 StartDate 仅显示为日期,例如, 2015/9/30

In my one ASP.NET Core app, a View is using following ViewModel. The underlying model of the ViewModel has an attribute StartDate. The model has DataAnnotion on StartDate but I'm not using the same DataAnnotation on the StartDate in ViewModel since I thought if DataAnnotation is in your Model then it gets aggregated to your viewmodels. And hence, the following View should display the StartDate as Date only. But the View is displaying StartDate as date and time, e.g. 9/30/2015 12:00:00 AM. On the other hand if I use DataAnnotation [DataType(DataType.Date)] on StartDate attribute in the ViewModel as well, the View correctly displays the StartDate as date only, say, 9/30/2015.

问题:为什么<$ c $ Model 上的c> DataAnnotation 是否未汇总到 ViewModel

Question: Why DataAnnotation on the Model is not getting aggregated to ViewModel?

模型

...
[DataType(DataType.Date)]
public DateTime StartDate { get; set; }
...

ViewModel

...
public DateTime StartDate { get; set; }
...

查看

...
@Html.DisplayFor(t => t.StartDate)
...


推荐答案

MVC使用某些DataAnnotation,EntityFramework使用某些DataAnnotation(其他由其他框架使用,因此不只是EF和MVC)。两者都使用了一些。例如,由于不同的原因,EF和MVC都使用了[Required]。 EF用它来表示不可为空。 MVC使用它来表示需要在文本框中输入值。但是,DataType属性和许多其他类型仅是MVC。我知道这很混乱,对于哪种注释针对哪种技术似乎也没有很好的参考。

Some DataAnnotations are used by MVC, some are used by EntityFramework (others are used by other frameworks, so it's not just EF and MVC). Some are used by both. For instance, [Required] is used by both EF and MVC, but for different reasons. EF uses it to mean non-nullable. MVC uses it to mean "requires a value in the textbox". However, the DataType attribute and many other types are MVC only. I know it's confusing, and there seems to be no good reference for which annotations are for which technology.

这是为什么您需要从视图中分离数据模型的一个很好的理由楷模。您可能需要在数据模型上添加特定的注释(例如[Required]),但不希望在ViewModel中使用它(例如,因为您不希望在字段中接受任何值,而是在代码后方提供值)。 ..

And this is a good reason why you need separate data models from view models. You may need a particular annotation on your data model (like [Required]) but don't want it in your ViewModel (because you want to accept no value in a field, and supply the value in a code-behind, for instance...

这篇关于为什么此ASP.NET Core DataAnnotation在ViewModel中有效,而在Model中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆