asp.net-mvc - MVC3在opera中将值设置为文本框类型日期时间

标签 asp.net-mvc asp.net-mvc-3 datetime input textbox

我的 ASP.NET MVC3 应用程序中有日期时间输入:

<div class="editor-field">
    @Html.EditorFor(model => model.Article.PublishedDate)
    @Html.ValidationMessageFor(model => model.Article.PublishedDate)
</div>

在 Opera 中,它对日期和时间进行特殊输入,但当我编辑模型时,它是空的,我想将其设置为值。在其他浏览器中,它是常规文本框并且设置了日期时间。感谢生成的代码是:

<input class="text-box single-line" data-val="true" data-val-required="Publish date is required" id="Article_PublishedDate" name="Article.PublishedDate" type="datetime" value="30.3.2012 10:00:00" data-default-value=""/>

如何修复它并在 Opera 中设置日期时间?

最佳答案

您需要根据RFC3339格式化您的日期时间标准

HTML5 输入日期时间规范:http://dev.w3.org/html5/markup/input.datetime.html

因此您的值需要采用如下格式:

<input ... type="datetime" value="2012-03-30T10:00:00" ... />

要将日期格式化为 RFC3339,您可以调用:

DateTime.ToString("yyyy-MM-ddThh:mm:ssZ");

您可以通过向 Article.PublishedDate 添加 DisplayFormatAttribute 来实现此目的:

[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-ddThh:mm:ssZ}")]
public DateTime PublishedDate { get; set; }

现在的问题(至少对我来说)是该属性现在始终保持这样的格式。您可以为此使用 EditorFor 模板:

@model DateTime?

@{
    var attributes = new Dictionary<string, object>();

    attributes.Add("type", "datetime");

    attributes.Add("class", "text-box single-line");

    //since this is a constraint, IsRequired and other constraints 
    //won't necessarily apply in the browser, but in case script 
    //turns off readonly we want the constraints passed
    if (ViewData.ModelMetadata.IsReadOnly)
    {
        attributes.Add("readonly", "readonly");
    }

    if (ViewData.ModelMetadata.IsRequired)
    {
        attributes.Add("required", "required");
    }
}
@Html.TextBox("", Model.HasValue ? Model.Value.ToUniversalTime().ToString("yyyy-MM-ddThh:mm:ssZ") : String.Empty, attributes)

基于DateTime.cshtml

对于本地日期:

@model DateTime?
@{
  var attributes = new Dictionary<string, object>();

  attributes.Add("type", "datetime-local");
  attributes.Add("class", "text-box single-line");

  if (ViewData.ModelMetadata.IsRequired)
  {
    attributes.Add("required", "required");
  }
}
@Html.TextBox("", Model.HasValue ? Model.Value.ToLocalTime().ToString("yyyy-MM-ddTHH:mm:ss") : String.Empty, attributes)

基于DateTime-Local.cshtml

关于asp.net-mvc - MVC3在opera中将值设置为文本框类型日期时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9940400/

相关文章:

javascript - Inversify.js - Reflect.hasOwnMetadata 不是函数

c# - 为什么我重新实现的方法保留了基类的属性?

asp.net-mvc-3 - MVC3 属性验证问题

asp.net-mvc - 流畅的 API 和数据注释

c# - Razor 引用未在 MVC 5 View 中解析 Visual Studio 2015 Enterprise

c# - 使用 MongoDB 更新内部列表

asp.net-mvc-3 - ASP.NET MVC 3 : Purpose of IgnoreRoute ("{resource}.axd/{*pathInfo}"); ? 已弃用?

c# - 如何避免 .NET 中从 Unix 时间戳转换为 DateTime 并返回的精度损失?

python - 使用 pd.to_datetime 将字符串日期转换为日期时间格式时出错

perl - 需要在 Perl 中比较时间;如何处理时区?