使用String格式在MVC中绑定可为空的日期时间

时间:2013-11-08 06:55:19

标签: c# asp.net-mvc

我无法解决过去两天的问题。

@Html.TextBoxFor(model => model.myObject.dateAssign, String.Format("{0:MM/dd/yy}"))

这里,dateAssign是可以为空的datetime。它可能是也可能没有价值。

我一直收到以下错误

Index (zero based) must be greater than or equal to zero and less than the size of the argument list.

请给我一些提示或指示

1 个答案:

答案 0 :(得分:4)

String.Format()需要第二个参数(see documentation) - 在您的情况下是您的日期。

请查看this page日期格式。

然后你会写类似

的东西
@Html.TextBox(model => String.Format("{0:MM/dd/yy}", model.myObject.dateAssign))  

或者,如果你想使用@Html.TextBoxFor,你可以这样注释你的财产:

// in your model:
[DisplayFormat(DataFormatString = "{0:MM/dd/yy}", ApplyFormatInEditMode= true]
DateTime? dateAssign { get; set; }  

// and in your view:
@Html.TextBoxFor(model => model.myObject.dateAssign)