[英]Model attribute validation issue
I am formatting DateTime?
我正在格式化
DateTime?
field like dd/MM/yyyy
and when I submit form it shows validation error. 字段,如
dd/MM/yyyy
,当我提交表单时显示验证错误。
I cannot get it why is it happens? 我不明白为什么会这样?
Model 模型
[Display(Name = "Expected Ending Time")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime? ExpectedEndingTime { get; set; }
HTML 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>
I think that DataFormatString is used just for displaying, and it doesn't use by ModelBinder for parsing. 我认为DataFormatString仅用于显示,而ModelBinder并不用于解析。 So your server still uses Culture from web.config.
因此,您的服务器仍然使用来自web.config的Culture。
You can hardcode specific culture in config that should be used with this date format. 您可以在该日期格式中使用的配置中对特定区域性进行硬编码。
Here is an answer that can help you - https://stackoverflow.com/a/8035636/169635 It has a sample of IModelBinder that uses CurrentCulture for parsing. 这里有一个答案,可以帮助您- https://stackoverflow.com/a/8035636/169635它使用的CurrentCulture解析IModelBinder的样本。 You can specify own format
您可以指定自己的格式
Nothing was useful for me guys.... 没什么对我有用...
So I added 1 extra field to the Model and will keep DateTime
like a String
in the format I need. 因此,我向模型添加了1个额外的字段,并将
DateTime
像String
一样保留了所需的格式。
And for places I need DateTime
format I have another field. 对于需要
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.