Why this ASP.NET Core DataAnnotation works in ViewModel but not in Model alone

隐身守侯 提交于 2019-12-12 04:57:10

问题


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.

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

Model

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

ViewModel

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

View

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

回答1:


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.

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...



来源:https://stackoverflow.com/questions/45382084/why-this-asp-net-core-dataannotation-works-in-viewmodel-but-not-in-model-alone

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!