简体   繁体   中英

How to pre-populate date field dotnet core razor pages?

I'm trying to pre-populate a date form field with today's date on a scaffolded Razor Pages form. I've tried setting class variables in the OnGet function, and I've also tried setting the value (below) or even the placeholder. No luck.

.Net Core 3.0 C# web application razor pages (not mvc).

Both of the following date pickers show the correct date in the value when I view the page source, but when the pages loads all I get is mm/dd/yyyy in the picker. I want it to show that date to the user on page load.

<input asp-for="VideoAccess.AccessStartDate" value="@DateTime.Now" class="form-control" />
<input type="datetime-local" value="@DateTime.Now.ToString()" class="form-control" />

All wrapped in the visual studio generated code scaffold. Any ideas?

You just assign today's date to the datetime property of your page model before you return the page in OnGet() method, and then return the page.

Let's demonstrate this by using Microsoft's Razor Pages with Entity Framework Core in ASP.NET Core Tutorial Instructor Entity

For example, lets look at the relevant parts from Create Page and PageModel

Pages/Instructors/Create.cshtml:

<div class="form-group">
    <label asp-for="Instructor.HireDate" class="control-label"></label>
    <input asp-for="Instructor.HireDate" class="form-control"/>
    <span asp-validation-for="Instructor.HireDate" class="text-danger"></span>
</div>

Pages/Instructors/Create.cshtml.cs: (Removed irrelevant parts)

    [BindProperty]
    public Instructor Instructor { get; set; }

    public IActionResult OnGet()
    {
        Instructor ??= new Instructor{ HireDate = DateTime.Now };
        return Page();
    }

This line Instructor??= new Instructor{ HireDate = DateTime.Now }; assigns current datetime value to the model-bound property Instructor . The page handles the rest.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM