DateTime Data Annnotations do not work in ASP.NET Core RC2 application

烂漫一生 提交于 2019-12-04 23:52:52

问题


if I add Data annotations to my ViewModel the value of the DateTime field is always {1/1/0001 12:00:00 AM}.

ViewModel

public class EditReleaseViewModel : BaseViewModel
{
        [Display(Name = "ReleaseDate", ResourceType = typeof(SharedResource))]
        [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd.MM.yyyy HH:mm}")]
        [Required(ErrorMessageResourceName = "FieldRequired", ErrorMessageResourceType = typeof(SharedResource))]
        public DateTime ReleaseDate { get; set; }
}

The controller is very straightforward, if I remove the data annotation and use the default everything works fine.

Controller

[HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(EditReleaseViewModel viewModel)
        {
            if (ModelState.IsValid)
            {
                ...
            }
        }

View

<div class="form-group col-sm-12 col-md-6 col-lg-4">
            <label asp-for="ReleaseDate" class="col-md-3 control-label"></label>
            <div class="col-md-9">
                <input asp-for="ReleaseDate" class="form-control" />
                <span asp-validation-for="ReleaseDate" class="text-danger" />
            </div>
        </div>

It is an ASP.NET Core MVC RC2 application - perhaps I'm missing something there.


回答1:


Change DateTime to DateTime? in your model.




回答2:


I figured this on my own way:

Add another data annotation [DataType(DataType.Date)], and then 'Build' the project, and then everything works.

I don't know way but it works for me.

BTW, I'm following the tutorial here: https://docs.asp.net/en/latest/tutorials/first-mvc-app/adding-model.html



来源:https://stackoverflow.com/questions/37963064/datetime-data-annnotations-do-not-work-in-asp-net-core-rc2-application

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