Search code examples
c#razorweb-applicationsrazor-pages

How to preserve a datepicker value?


So i have a daterpicker. I was asked to make the datepicker remember the date it was given when you were using it to search for a date. The codes:

[BindProperty, DataType(DataType.Date)]
        public DateTime Date { get; set; }

    <form method="post" asp-page-handler="TestClick">
        <br />
        <br />
        <input type="date" data-val="true" data-val-required="The Date field is required." id="Date" name="Date" value="yyyy-mm-dd" />
        <button>Search</button>
        <br />

    </form>

from a .cshtml file

public void OnPostTestClick()
        {
            String testDate = Request.Form["Date"];
            Debug.WriteLine("Testclick verdi2 = " + testDate);
            filterdato = testDate;
            ListData();
        }

from .cshtml.cs file

I was told where the code should probably be, but I don't know how to do it. IS there anyone that could help me to figure this out?


Solution

  • Use an input tag helper for rendering the date input. The following is all you need:

    <input asp-for="Date" />
    

    See more about working with dates and times in Razor Pages forms on my site: https://www.learnrazorpages.com/razor-pages/forms/dates-and-times

    Also, you don't need to reference Request.Form. You can rely on Model binding to bind the posted value to your Date property:

    public void OnPostTestClick()
    {
        Debug.WriteLine("Testclick verdi2 = " + Date);
        filterdato = testDate;
        ListData();
    }
    

    Here's more about model binding: https://www.learnrazorpages.com/razor-pages/model-binding