【问题标题】:HTML 5 Input date not showing the value specifiedHTML 5 输入日期未显示指定的值
【发布时间】:2019-10-05 02:34:54
【问题描述】:

NET Core** 项目和在我编辑记录的一个页面中,<input type="date"> 没有显示我在 Razor 中创建视图时传递的值。

这是我的 Razor 代码:

<div class="input-group">
    <div class="input-group-prepend">
        <i class="input-group-text fa fa-user"></i>
    </div>
    @Html.TextBoxFor(model => model.NewPriceList.PriceFrom, 
                     new { @class = "form-control", @type = "date", 
                           @Value = Model.NewPriceList.PriceFrom })
</div>

这就是我在以 HTML 形式创建的 Google Chrome 开发人员工具中看到的内容

<input class="form-control" data-val="true" 
       data-val-required="The Obwiązuje od field is required." 
       name="NewPriceList.PriceFrom" type="date" 
       value="2/15/2019 12:00:00 AM">

但由于某种原因,它没有正确渲染,这就是我得到的:

【问题讨论】:

    标签: c# html date asp.net-core razor


    【解决方案1】:

    您需要指定rfc3339 format

    @Html.TextBoxFor( 模型 => 模型.NewPriceList.PriceFrom , "{0:yyyy-MM-dd}", 新的 { @type="日期", @class= “表单控制” @value = Model.NewPriceList.PriceFrom } )

    或者如果你只是想使用模型来渲染值,你不必指定@value=

    @Html.TextBoxFor( 模型 => 模型.NewPriceList.PriceFrom , "{0:yyyy-MM-dd}", 新的 { @type="日期", @class= “表单控制” } )

    或者干脆使用InputTagHelper:

    <input asp-for="NewPriceList.PriceFrom" class = "form-control" >
    

    如果您使用[DataType(DataType.Date)] 属性注释,InputTagHelper 将自动为您选择正确的格式。

    【讨论】:

      【解决方案2】:

      将日期格式化为 ShortDate。 DateControl 不喜欢一天中的时间:

      <input class="form-control" data-val="true"
             data-val-required="The Obwiązuje od field is required."
             name="NewPriceList.PriceFrom" type="date"
             value=@DateTime.Now.ToShortDateString()>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-08-12
        • 2020-05-02
        • 2021-07-17
        • 1970-01-01
        • 1970-01-01
        • 2020-04-10
        相关资源
        最近更新 更多