我正在创建接受开始日期和结束日期的表格。当创建按钮按下时,它接受日期时间中的值,并且用户会看到输入日期的日历格式。但是当我单击编辑时,表单会显示除日期之外的所有详细信息。 这是我的代码。 型号:
public DateTime whenEntred { get; set; } = DateTime.UtcNow;
public DateTime whenModified { get; set; } = DateTime.UtcNow;
编辑:
<div class="row">
<div class="col-md-5">
@Html.EditorFor(model => model.startDate, new { htmlAttributes = new { @class = "form-control startDate", @autoComplete = "off", @type = "date", @required = "required" } })
@Html.ValidationMessageFor(model => model.startDate, "", new { @class = "text-danger" })
</div>
<div class="col-md-5">
@Html.EditorFor(model => model.endDate, new { htmlAttributes = new { @class = "form-control endDate", @autoComplete = "off", @type = "date", @required = "required" } })
@Html.ValidationMessageFor(model => model.endDate, "", new { @class = "text-danger" })
</div>
</div>
我想以日历格式显示日期,用户也可以编辑该日期。 我必须做哪些改变?请帮忙。
(在检查编辑中显示为:
<input autocomplete="off" class="form-control startDate text-box single-line" data-val="true" data-val-date="The field Start Date must be a date." data-val-required="The Start Date field is required." id="startDate" name="startDate" required="required" type="date" value="01-08-2022 00:00:00">
)
这是因为
input type="date"
接受 yyyy-MM-dd
格式。
您可以先将日期格式转换为
yyyy-MM-dd
,然后再传递给查看。
Model Class
public class EditVM
{
// Add using System.ComponentModel.DataAnnotations; on top of the model class
[Required]
[DataType(DataType.Date)]
public string startDate { get; set; }
[Required]
[DataType(DataType.Date)]
public string endDate { get; set; }
}
您传递给视图的模型,将
startDate and endDate
的数据类型转换为string
Controller
[HttpGet]
public ActionResult Edit(int Id)
{
var model = ...;
model.startDate = model.startDate.Date.ToString("yyyy-MM-dd");
model.endDate = model.endDate.Date.ToString("yyyy-MM-dd");
return View(model);
}
是的,因为输入 type="date" 接受 yyyy-MM-dd 格式。 您可以在视图中添加预期的格式,如下所示:
@Html.TextBoxFor(model => model.fromDate, "{0:yyyy-MM-dd}", new { type="date", @class = "form-control",value = @Model.fromDate })
在模型中您可以保留日期时间类型
实现此目的的一个简单方法是在设计器端的绑定过程中修改数据,如下所示。
<asp:TextBox ID="tbDate" TextMode="Date" runat="server" Text='<%# Bind("YourColumnData", "{0:yyyy-MM-dd}") %>' CssClass="w-auto"></asp:TextBox>