【问题标题】:How do you format a DateTime that's displayed by TextBoxFor() in MVC3?如何格式化 MVC3 中 TextBoxFor() 显示的 DateTime?
【发布时间】:2012-12-05 14:08:22
【问题描述】:

我已经安装了 ASP.NET MVC3。我需要带有格式化日期的日期选择器。我试过这个,但它不起作用(当传递“{0:dd/MM/yyyy}”作为格式参数时,它仍然不格式化):

    private static MvcHtmlString FormattedDateTextBoxFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, string format, RouteValueDictionary htmlAttributes)
    {
        var metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);

        if (metadata.Model != null && metadata.Model as DateTime? != null)
            htmlAttributes.Add("value", string.Format(format, (DateTime)metadata.Model));

        return htmlHelper.TextBoxFor(expression, htmlAttributes);
    }

编辑:如果格式为“{0:dd-MM-yyyy}”,我的代码有效,但不仅适用于“{0:dd/MM/yyyy}”

我知道 MVC4 已经有了这个功能,但不幸的是我的项目是在 MVC3 上编写的。你能帮帮我吗?

【问题讨论】:

标签: c# asp.net-mvc asp.net-mvc-3 formatting


【解决方案1】:

我什至可以使用的唯一格式是:

@Html.TextBoxFor(m => m.Birthdate, "{0:MM/dd/yyyy}")

【讨论】:

【解决方案2】:

语法是: @Html.TextBoxFor(表达式,字符串格式,对象htmlAttributes)

例如:

   @Html.TextBoxFor(x => x.DateUtc, "{0:yyyy-MM-dd HH:mm:ss}",
            new { @class = "form-control", placeholder = "Enter Title", id="myDate"})

【讨论】:

  • 这对我来说非常有用。与其硬编码日期格式,不如使用"{0:d}" 作为字符串格式,根据客户端的区域设置,render the date 可能会更好。
【解决方案3】:

在您的模型中,使用以下内容:

[DisplayFormat(DataFormatString="{0:dd/MM/yyyy}")]
public DateTime YourDate { get; set; }

这是它应该在视图中执行的操作:

@Html.EditorFor(model => model.YourDate, new { @class = "date" })

这应该会给你一个格式化为 dd/MM/yyyy 格式的日期。

【讨论】:

  • 你的意思是[DisplayFormat(DataFormatString="{0:dd/MM/yyyy}")]
  • 是的,我的错。对于那个很抱歉。直接从我的代码中复制,并没有注意到您的格式略有不同。对于那个很抱歉。顺便说一句,这行得通吗?
  • 你知道 EditorFor 没有 htmlAttribues 参数!
  • 为我工作,但你知道你不需要 'DataType' 属性!
  • 是的,后来我意识到了这一点,但从未编辑过我的原始帖子。谢谢。
【解决方案4】:

显示将取决于文化。虽然在大多数情况下所有其他答案都是正确的,但它对我不起作用。如果附加了 jQuery datepicker,文化问题也会导致不同的问题。

如果您希望通过以下方式强制格式转义 /:

@Html.TextBoxFor(model => model.YourDate, "{0:MM\\/dd\\/yyyy}")

如果没有为我转义,它会显示 08-01-2010 与预期的 08/01/2010

如果没有转义,jQuery datepicker 也会选择不同的 defaultDate,在我的例子中是May 10, 2012

【讨论】:

    【解决方案5】:

    这种格式会帮助你:

    @Html.TextBoxFor(Model => Model._facadeLowdown.DoB, new { @value= Model._facadeLowdown.DoB.HasValue ? Model._facadeLowdown.DoB.Value.ToString("MM/dd/yyyy") : ""
    }
    

    【讨论】:

      猜你喜欢
      • 2013-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-11
      • 2011-03-28
      • 2014-04-30
      • 2012-07-18
      • 2012-03-01
      相关资源
      最近更新 更多