Search code examples
c#asp.net-corerazor-pages

How to convert ViewData which is containing datetime value in it inside view(Razor) and assign to datetime picker input field(datetime-local)


Controller code -

ViewData["fromDate"] = formcollection.fromDate; (no doubt i am able to see the viewdata value in javascript)

.cshtml view- <input type="datetime-local" id="fromDate" value="@ViewData["fromDate"] />

Above assignment is not working.


Solution

  • <input type="datetime-local" id="fromDate" value="@(((DateTime)ViewData["fromDate"]).ToString("yyyy-MM-dd"))" />
    

    However, if you are using ASP.NET Core, you should use a ViewModel and input tag helpers. Then you set the format string on the tag helper and it takes care of formatting the date correctly:

    public class MyViewModel
    {
        // various properties for the view
        public DateTime FromDate {get;set;}
    }
    

    Then your tag helper:

    <input asp-for="FromDate" asp-format="yyyy-MM-dd" />
    

    Note that the format must be yyyy-MM-dd according to RFC 3339. The datetime-local control will take care of presenting the value in the locale of the user.

    I've blogged here about working with DateTimes in ASP.NET Core. It's Razor Pages focused, but the principles apply to MVC too: https://www.mikesdotnetting.com/article/352/working-with-dates-and-times-in-razor-pages-forms