如何格式化MVC3中TextBoxFor()显示的DateTime?

时间:2012-12-05 14:08:23

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

我安装了ASP.NET MVC3。我需要带有格式化日期的datepicker。我尝试了这个,但它没有工作(当传递“{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上编写的。你能救我吗?

5 个答案:

答案 0 :(得分:41)

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

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

答案 1 :(得分:10)

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

例如:

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

答案 2 :(得分:3)

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

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

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

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

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

答案 3 :(得分:2)

此格式可以帮助您:

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

答案 4 :(得分:0)

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

如果您希望以下列方式强制格式转义:

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

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

如果没有转义,jQuery datepicker将选择不同的defaultDate,在我的实例中它是May 10, 2012