如何使用输入类型=日期的Html.TextBoxFor?

Ang*_*ker 20 c# asp.net-mvc html5 input

我想在我的代码中实现.为此,我有以下内容:

@Html.TextBoxFor(model => model.CreationDate, new { @type = "date" })
Run Code Online (Sandbox Code Playgroud)

此代码生成以下HTML:

<input data-val="true" data-val-date="The field CreationDate must be a date." 
             data-val-required="The CreationDate field is required." 
             id="CreationDate" name="CreationDate" type="date" 
             value="09/05/2012 15:02:19">
Run Code Online (Sandbox Code Playgroud)

该值未显示在网页上,因为type ="date"需要YYYY-MM-DD格式的数据.

我已经尝试过格式化日期,但当然会爆炸.

@Html.TextBoxFor(model => model.CreationDate.ToString("YYYY-MM-DD"), 
                 new { @type = "date" })
Run Code Online (Sandbox Code Playgroud)

如何使用TextBoxFor方法正确显示构造?或者我应该使用其他方法(我已经尝试过EditorFor但失败了)?

CreationDate 是DateTime类型.

Sar*_*nga 54

试试这个;

@Html.TextBoxFor(model => model.CreationDate,
           new { @type = "date", @Value = Model.CreationDate.ToString("yyyy-MM-dd") })
Run Code Online (Sandbox Code Playgroud)

null设置值时必须处理.

要么

如果你可以改变Model你可以试试这个;

[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime CreationDate{ get; set; }
Run Code Online (Sandbox Code Playgroud)

在您的视图中,您可以使用EditorFor帮助程序.

@Html.EditorFor(model => model.CreationDate, new { @type = "date" })
Run Code Online (Sandbox Code Playgroud)

  • 不要使用第一个选项(在使用`HtmlHelper`方法时从不设置`value`属性 - 你失去了真正的双向模型绑定 - 正确的用法是`@ Html.TextBoxFor(model => model.CreationDate,"{ 0:yyyy-MM-dd}",new {type ="date"})`和第二个选项只需要`@ Html.EditorFor(model => model.CreationDate)` - `type ="date"由于`[DataType(DataType.Date)]`属性,``已经被`EditorFor()`方法添加了` (10认同)