【问题标题】:Model attribute validation issue模型属性验证问题
【发布时间】:2014-01-15 17:29:52
【问题描述】:

我正在格式化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>

【问题讨论】:

  • 如果输入 MM/dd/yyyy 值,会起作用吗?如果是,那么不知何故您的格式不适用
  • 您能将 ExpectedEndingTime 类型从 DateTime 更改为 String 并检查您从浏览器获得的值吗?
  • 可能是使用可为空的值导致此问题。
  • 这也可能与您的 MVC 应用程序中的区域设置有关。您是否尝试过查看01/15/2014 是否有效?
  • 你用什么DataPicker?

标签: c# .net asp.net-mvc validation displayformat


【解决方案1】:

我认为 DataFormatString 仅用于显示,ModelBinder 不使用它进行解析。所以你的服务器仍然使用 web.config 中的文化。

您可以在配置中硬编码应与此日期格式一起使用的特定文化。

这是一个可以帮助你的答案 - https://stackoverflow.com/a/8035636/169635 它有一个使用 CurrentCulture 进行解析的 IModelBinder 示例。您可以指定自己的格式

【讨论】:

  • 感谢您的意见!我做了一些调查,但最后我得到了另一个解决方案。
【解决方案2】:

没有什么对我有用....

所以我在 Model 中添加了 1 个额外字段,并将 DateTimeString 一样保留为我需要的格式。

对于我需要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; }  

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多