Search code examples
c#asp.net-coreasp.net-core-mvc

How to pre-populate a 'date' input field with Razor/C# values


I have a 'date' type input, and I'm trying to get the Razor code to pre-fill the date with information that the server already has, because it's for an Edit field on an MVC ASP.NET Core app I'm working on.

The code I'm using is:

<input type="date" name="DeliveredDate" id="DeliveredDate" value='@Model["order"].DeliveredDate.ToString("mm/dd/yyyy")'>

I can get the code to show the string in any other part of the page, but is there a trick to getting that same string to populate the value of a date field? All my googling hasn't turned up anything particularly helpful.


Solution

  • Because HTML's <input type="date" /> requires the yyyy-MM-dd format for its value="" attribute you can use either @Html.TextBox() or strongly-typed @Html.TextBoxFor() helper to do so, by either setting DisplayFormatAttribute or date format directly in the helper:

    Viewmodel property

    [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
    public DateTime DeliveredDate { get; set; }
    

    View

    @Html.TextBox("DeliveredDate", Model["order"].DeliveredDate, "{0:yyyy-MM-dd}", new { type = "date" })
    
    @Html.TextBoxFor(model => model.DeliveredDate, "{0:yyyy-MM-dd}", new { type = "date" })
    

    Or using EditorFor by setting date format, which automatically appends type = "date" attribute:

    @Html.EditorFor(model => model.DeliveredDate)
    

    If you're using tag helper, just set asp-for attribute:

    <input asp-for="DeliveredDate" type="date" />
    

    Notes:

    1. Make sure that you're already set the date value inside controller action, e.g. model.DeliveredDate = DateTime.Now (model has type of Model["order"]).

    2. The latter approach requires setting DisplayFormatAttribute in viewmodel property because there's no string formatting parameter to set the format from EditorFor or tag helper itself.