【问题标题】:C# MVC EditorFor does not show passed valueC# MVC EditorFor 不显示传递的值
【发布时间】:2019-12-10 08:08:37
【问题描述】:

我认为这很容易,但是在编辑框中显示传递的值时遇到了一些问题。

我将一些带有模型的默认日期时间传递给查看,我想使用EditorFor,因为它有很好的日历选择器而不是简单的TextBoxFor

我的ReportQuery.cs

    public class ReportQuery
    {
        [DisplayFormat(DataFormatString = "{0:g}", ApplyFormatInEditMode = true)]
        [Display(Name = "Since")]
        [BindRequired]
        public DateTime? Since { get; set; }

        [DisplayFormat(DataFormatString = "{0:g}", ApplyFormatInEditMode = true)]
        [Display(Name = "To")]
        [BindRequired]
        public DateTime? To { get; set; }
    }

我的RaportQuery.cshtml - 这是部分视图

@model Castle.Feedback.Service.Models.ArticleViewer.ReportQuery

<form class="form-inline" asp-controller="ArticleViewer" asp-action="ReportExport" method="GET">
    <table class="edit-table">
        <tr>
            <th><span>@Html.EditorFor(model => model.Since, new { @Value = DateTime.UtcNow.Date.AddMonths(-1) })</span></th>
            <th><span>@Html.EditorFor(model => model.To, new { @Value = DateTime.UtcNow.Date.AddDays(1).AddTicks(-1) })</span></th>
        </tr>
    </table>
    <button type="submit" class="btn btn-link">Generate</button>
</form>

但正如您所见,默认值在TextBoxFor 中,而不是在漂亮的EditorFor 中。你知道如何在EditorFor 传递值中显示吗?

【问题讨论】:

  • 这通常意味着尝试的日期值与浏览器预期的格式不匹配。例如,Chrome 默认为ISO-8601 date。不确定您的页面的文化设置或您使用的任何浏览器的实例如何影响这一点。
  • 您在某处有DateTime.cshtml 视图吗?如果是这样,您能否将其包含在您的问题中?
  • 我在主要问题中添加了我的观点。当我在视图中使用“价值”时,它甚至不起作用。
  • Html.EditorFor 将尝试从EditorTemplates(在Views/Shared 或当前控制器文件夹中具有该名称的文件夹中)加载与类型名称匹配的视图您正在绑定的字段。那么,您在某处有DateTime.cshtml 吗?如果是这样,看看您是否应用了任何自定义格式会很有帮助。
  • 是的,"{0:g}" 会导致在浏览器中显示的问题。如果您希望它不管用户的语言/文化设置如何都能正常工作,可能需要"{0:s}",这是我之前提到的 ISO-8601 格式(参见docs.microsoft.com/en-us/dotnet/standard/base-types/…

标签: c# asp.net-mvc razor datepicker


【解决方案1】:

根据我的经验,大多数/所有实际实现日期选择器控件(或以任何方式支持&lt;input type="date" /&gt; 输入)的浏览器都要求输入的值采用 ISO-8601 定义的唯一“通用”模式.

.NET 有一个standard format identifier,您可以使用s 来应用此格式,如下所示:

@Html.TextFor(model => model.Since, "{0:s}", new { @type = "date" })

如果您只想要值的日期部分,您可以为 ISO-8601 短日期使用自定义格式:

@Html.TextFor(model => model.Since, "{0:yyyy-MM-dd}", new { @type = "date" })

如果您使用这种格式,您的 DateTime 值将在发布到控制器时将 00:00:00 作为值的时间部分。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-20
    • 1970-01-01
    • 2014-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-27
    相关资源
    最近更新 更多