Search code examples
c#asp.net-mvcrazordatepicker

C# MVC EditorFor does not show passed value


I thought that this would be easy, but I have got problems showing the passed value in the editor box.

I pass some default DateTime in a Model to a View and I want to use EditorFor, because it is have nice calendar picker instead of simple TextBoxFor.

My 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; }
    }

My RaportQuery.cshtml - is a partial view

@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>

But as you can see, default value is in TextBoxFor, but not in nice EditorFor. Do you have any idea how can I show the passed value in EditorFor?

image description here


Solution

  • From my experience, most / all browsers which actually implement a date-picker control (or support the <input type="date" /> input in any fashion) require the input's value to be in the only "universal" pattern, defined by ISO-8601.

    .NET has a standard format identifier you can use to apply this format, s, like so:

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

    If you only want the date part of the value, you can use a custom format for an ISO-8601 short date:

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

    If you use this format, your DateTime value will have 00:00:00 as the time part of the value when posting to the controller.