如何以日期格式显示 EditorFor 模型值

How can show the EditorFor model value with date format

我有 html 页面的给定模型来接受日期。我正在尝试将 datefrom 和 dateto 输入框格式化为“dd/mm/yyyy”格式。目前,它仅显示为文本格式。如何使两列都接受数据为 dd/mm/yyyy.

EditDateModel
public class EditDateModel
    {
        public string FromDate { get; set; }
        public string ToDate { get; set; }
        
    }

@model EditDateModel
<table id="tblEntry" class="table table-striped">
    <thead>
        <tr>
            <th>Date From</th>
            <th>Date To</th>
        </tr>
    </thead>
    <tbody>
 <tr>
            <td>@Html.EditorFor(model => model.FromDate, new { htmlAttributes = new { @class = "form-control datepicker w-100" } })</td>
            <td>@Html.EditorFor(model => model.ToDate, new { htmlAttributes = new { @class = "form-control w-100" } })</td>
  </tr>

    </tbody>
</table>

你在正确的轨道上,但这里的事情是...... asp.net mvc 只负责生成 HTML 资源,以及嵌入到它的所有脚本。 因此,您将始终获得文本值。

为了完成您的要求ui回复,我建议在 js 中使用第三个库,该库支持转换实际 ui 交互日期格式。例如,我将使用 jquery 和 datepicker

// This is up at your HTML
<td>@Html.EditorFor(model => model.FromDate, new { htmlAttributes = new { @class = "form-control datepicker w-100" } })</td>

// And this should be on your js below that
$(document).ready(() => {
            $('.datepicker').datepicker({
                format: "dd/mm/yyyy"
            });
        });
// Please don't forget to embed the library somewhere

您不需要使用任何其他库。您可以使用 asp.net DataAnnotations 它推荐的、方便且易于使用的方法来完成。

Implementation:

使您的 EditDateModel 如下所示:

public class EditDateModel
    {
        [DataType(DataType.Date, ErrorMessage = "Date only")]
        [DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]
        public string FromDate { get; set; }

        [DataType(DataType.Date, ErrorMessage = "Date only")]
        [DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]
        public string ToDate { get; set; }
    }

Note: It would require using System.ComponentModel.DataAnnotations; reference on your package reference on the top.

Views:

<table id="tblEntry" class="table table-striped">
    <thead>
        <tr>
            <th>Date From</th>
            <th>Date To</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>@Html.EditorFor(model => model.FromDate, new { htmlAttributes = new { @class = "form-control datepicker w-100" } })</td>
            <td>@Html.EditorFor(model => model.ToDate, new { htmlAttributes = new { @class = "form-control datepicker w-100" } })</td>
        </tr>

    </tbody>
</table>

注: 你的 FromDate 格式是正确的 我制作 Todate 的格式与此相同 @class = "form-control datepicker w-100"

OutPut:

如果您想获得更多知识,可以参考我们的official documet here. For any type date format issue you could also refer this

希望它能解决您的问题。