Mvc 5 在编辑日期值时,如果我用 Box 填充它,则不允许我选择新日期

Mvc 5 While Editing the Date value, Box do not let me choose new date if i fill it with

我有日期字段,我希望它用当前值填充并让我同时选择日期,但这没有发生。 当我像这样对 EditorFor 行执行 model.CourseDate.Date 时:

   <div class="form-group">
        @Html.LabelFor(model => model.CourseDate, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.CourseDate.Date, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.CourseDate, "", new { @class = "text-danger" })
        </div>
    </div>

这会发生

如果我这样做 labelfor

    <div class="form-group">
        @Html.LabelFor(model => model.CourseDate, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.CourseDate, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.CourseDate, "", new { @class = "text-danger" })
        </div>
    </div>

发生这种情况:

我要填写字段,同时我可以从下拉列表中选择日期。

这里有两种不同的表示方式:

1) 在第一个 EditorFor 上,它作为 CourseDateDateTime 实例的一部分指向 Date property,因此它呈现为 [=19] 的纯文本框=].因此,

@Html.EditorFor(model => model.CourseDate.Date, new { htmlAttributes = new { @class = "form-control" } })

呈现如下:

<input id="CourseDate_Date" name="CourseDate.Date" type="datetime" value="...">

2) CourseDate 视图模型 属性 的第二个 EditorFor 边界定义为 DateTime,因此呈现 <input type="date" />。因此,

@Html.EditorFor(model => model.CourseDate, new { htmlAttributes = new { @class = "form-control" } })

呈现如下:

<input id="CourseDate" name="CourseDate" type="date" value="...">

由于您的 objective 允许用户直接在输入中编辑日期以及日期选择器选择,因此解决方法是使用 TextBoxFor 助手和 [=26= 中的 type="date" 属性].因此,您的日期输入格式应如下例所示:

@Html.TextBoxFor(model => model.CourseDate, "{0:yyyy-MM-dd}", new { @class = "form-control", type = "date" })

请注意,<input type="date" /> 元素需要格式为 yyyy-MM-dd 的值才能根据 HTML date specification 显示其值,因此字符串格式 {0:yyyy-MM-dd} 用于匹配该格式。

This fiddle 包含用户应该能够手动输入日期组件以及使用 <input type="date" /> 元素中的日期选择器的示例。

参考:

HTML Date Input (MDN)