【问题标题】:DataFormatString is not working数据格式字符串不起作用
【发布时间】:2017-06-18 12:37:13
【问题描述】:

我正在尝试将 DataFormatString 的格式从 dd/MM/yyyy 更改为 MM/yy。原因是因为我希望用户选择他们的信用卡到期日期。我将 HTML 分成两部分:模型和视图。

Order.cs

[Display(Name = "Expiration Date")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime Experation { get; set; }

地址和付款.cshtml

<div class="form-group">
    @Html.LabelFor(model => model.Experation, htmlAttributes: new { @class = "col-lg-2 control-label" })
    <div class="col-lg-10">
        @Html.EditorFor(model => model.Experation)
        @Html.ValidationMessageFor(model => model.Experation, "", new { @class = "text-danger" })
    </div>

以上代码是我尝试在我的模型中将其转换为 MM/yy。但是,结果仍然是 dd/MM/yyyy。这里有我不知道的错误吗?

【问题讨论】:

  • 删除[DataType(DataType.Date)],它添加了type-"date",如果支持,它将生成一个浏览器HTML5日期选择器(但它只在Chrome和Edge中支持,所以你必须使用其中之一)。
  • 但是你的格式字符串没有意义。该属性是 typeof DateTime 必须包含一个 day 组件,并且当您提交时,ModelState 将无效,Experation 的值将是 01/01/0001(如果您启用了客户端验证,则不会甚至可以提交表格)

标签: asp.net-mvc date asp.net-mvc-4 datepicker


【解决方案1】:

我认为任何内置的DataType 都不会处理像这样你只需要一个月和一年的情况。从某种意义上说,它并不是真正的日期,而是“月+年”的组合。我只是将其作为String 处理并使用正则表达式对其进行验证,然后在服务器上执行进一步的解析和验证。

请注意,下面的正则表达式绝对不是万无一失的,它只是为了捕捉明显的输入错误(例如 YY/MM 而不是 MM/YY)。由于选项范围有限,您可以使用 (01|02|03|04|05|06|07|08|09|10|11|12)\/(20|21|22|23|24|25|26|27|28|29|30|31|32|33) 之类的内容使其更严格。

[Display(Name = "Expiration Date")]
[RegularExpression("(0|1)[0-9]\/2[0-9]", ErrorMessage = "Enter expiration date using MM/YY format")]
public String Expiration { get; set; }

另一种方法是将字段拆分为两个数字字段ExpirationMonth 和ExpirationYear。同样,通过一些巧妙的Range 魔法,您可以将月份限制在 1 到 12 之间,将年份限制在 20 到 42 之间。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-22
    • 1970-01-01
    相关资源
    最近更新 更多