C# 模型属性验证问题
我正在格式化C# 模型属性验证问题,c#,.net,asp.net-mvc,validation,displayformat,C#,.net,Asp.net Mvc,Validation,Displayformat,我正在格式化DateTime?字段,如dd/MM/yyyy,提交表单时显示验证错误 我搞不懂为什么会这样 型号 [Display(Name = "Expected Ending Time")] [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")] public DateTime? ExpectedEndingTime { get; set; } HTML @Html.TextBox
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>
@Html.TextBoxFor(x=>x.requsion.ExpectedEndingTime,新{@class=“form control dataPickerField”,id=“ExpectedEndingTimeDataPicker”,@readonly=true})
@Html.ValidationMessageFor(x=>x.requsion.ExpectedEndingTime)
$(函数(){
$(“#ExpectedEndingTimeDataPicker”).datepicker({
格式:“dd/mm/yyyy”,
自动关闭:正确
})
.on('changeDate',功能(ev){
//做事;
);
});
我认为DataFormatString只用于显示,ModelBinder不使用它进行解析。因此您的服务器仍然使用web.config中的区域性
您可以在配置中硬编码应与此日期格式一起使用的特定区域性
这里有一个答案可以帮助你-
它有一个IModelBinder示例,使用CurrentCulture进行解析。您可以指定自己的格式。对我来说没有什么有用的 因此,我在模型中添加了一个额外字段,并将
日期时间
保留为字符串
的格式
对于需要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; }
如果您输入MM/dd/yyyy值,它会工作吗?如果是,那么您的格式可能不适用。您可以将ExpectedEndingTime类型从DateTime更改为String,并检查您从浏览器中获得的值吗?可能是使用可空值导致了此问题。这也可能与您的MVC应用程序中的区域设置有关。是否尝试查看如果
01/15/2014
有效?您使用什么数据采集器?感谢您的输入!我做了一些调查,但最终找到了另一个解决方案。