【问题标题】:MVC input DateTimeMVC 输入日期时间
【发布时间】:2013-11-10 23:04:01
【问题描述】:

如果我在 MVC 中使用 EditFor,我的 DateTime 字段会显示未格式化的日期时间,如果我使用旧式 html,我的字段不会收到错误类。

<div class="editor-field">
     <input type="text" name="EstimateTime" id="EstimateTime" value="<%: (Model != null) ? Model.EstimateTime.ToString("dd/MM/yyyy hh:mm:ss tt") : "" %>" />
     <%: Html.TextBoxFor(model => model.EstimateTime, new { @value = (Model != null) ? Model.EstimateTime.ToString("dd/MM/yyyy hh:mm:ss tt") : "" })%>
     <%: Html.ValidationMessageFor(model => model.EstimateTime) %>
</div>

result HTML:看值的区别:

<div class="editor-field">
    <input type="text" name="EstimateTime" id="EstimateTime" value="31/10/2013 01:54:42 PM" class="hasDatepicker">
    <input  id="EstimateTime" name="EstimateTime" type="text" value="10/31/2013 1:54:42 PM" class="input-validation-error text-box single-line">
    <span class="field-validation-error">Isn't a date/time valid</span>
</div>

修复它的最佳做法是什么?

【问题讨论】:

  • 它把日期换成了月份。有什么大不了的?
  • 问题是,如果我使用 Model.EstimateTime.ToString("dd/MM/yyyy hh:mm:ss tt") 日期显示格式为 MM/dd/.....

标签: asp.net-mvc


【解决方案1】:

DataFormatString 添加到模型中的属性中。

public class YourModel
{
   [DisplayName("Estimate Time:"), 
    DisplayFormat(DataFormatString = "{0:dd/MM/yyyy hh:mm:ss tt}")]
   public System.DateTime EstimateTime { get; set; }
   ...
}

【讨论】:

  • 您还应该在DisplayFormat 属性中指定ApplyFormatInEditMode = true
【解决方案2】:

我总是使用编辑器模板来完善输出控制

这是 DateTime.cshtml:

@model System.DateTime?

@{
    IDictionary<string, object> Attributes = new Dictionary<string, object>();
    if (ViewData.ContainsKey("style")) {
        Attributes.Add("style", (string)ViewData["style"]);
    }
    if (ViewData.ContainsKey("autohelp")) {
        Attributes.Add("title", (string)ViewData["autohelp"]);
    }
    if (ViewData.ContainsKey("autofocus")) {
        Attributes.Add("autofocus", (string)ViewData["autofocus"]);
    }
    Attributes.Add("class", "fecha");
    Attributes.Add("autocomplete", "off");
}


@Html.TextBox("", (Model.HasValue ? Model.Value.ToShortDateString() : string.Empty), Attributes)

【讨论】:

    【解决方案3】:
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")]
    [DataType(DataType.Date)]
    public System.DateTime EstimateTime { get; set; }
    

    这在最新版本的 Chrome 中对我有用

    【讨论】:

    • 我不认为 chrome 与它有任何关系。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-17
    • 1970-01-01
    • 2014-02-22
    相关资源
    最近更新 更多