[英]Model attribute validation issue
我正在格式化DateTime?
字段,如dd/MM/yyyy
,當我提交表單時顯示驗證錯誤。
我不明白為什么會這樣?
模型
[Display(Name = "Expected Ending Time")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime? ExpectedEndingTime { get; set; }
HTML
@Html.TextBoxFor(x => x.Requsition.ExpectedEndingTime, new { @class = "form-control dataPickerField", id = "ExpectedEndingTimeDataPicker", @readonly = true })
@Html.ValidationMessageFor(x => x.Requsition.ExpectedEndingTime)
<script>
$(function () {
$('#ExpectedEndingTimeDataPicker').datepicker({
format: 'dd/mm/yyyy',
autoclose: true
})
.on('changeDate', function (ev) {
// do things;
);
});
</script>
我認為DataFormatString僅用於顯示,而ModelBinder並不用於解析。 因此,您的服務器仍然使用來自web.config的Culture。
您可以在該日期格式中使用的配置中對特定區域性進行硬編碼。
這里有一個答案,可以幫助您- https://stackoverflow.com/a/8035636/169635它使用的CurrentCulture解析IModelBinder的樣本。 您可以指定自己的格式
沒什么對我有用...
因此,我向模型添加了1個額外的字段,並將DateTime
像String
一樣保留了所需的格式。
對於需要DateTime
格式的地方,我還有另一個字段。
[Display(Name = "Expected Ending Time")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime? ExpectedEndingTime { get; set; }
[Required]
[Display(Name = "Expected Ending Time")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
public string ExpectedEndingTimeAsString { get; set; }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.