Setting form value to C# Variable

blazor c# razor

Question

I have a basic entry form, I need to set the entryDate field to todays date automatically so that when the user hits submit, the database will autofill with todays date (As a string)

<input for="EntryDate" value=@entryDate class="form-control" bind="@ath.EntryDate"/>

@functions{
    EventAthlete ath = new EventAthlete();

    string entryDate = DateTime.Now.ToShortDateString();

    protected async Task AddAthlete()
    {
        await Http.SendJsonAsync(HttpMethod.Post, "/api/Athlete/Add", ath);

    }
}

I would expect from the above code that it would autofill the form with my entryDate variable?

Or better yet is there a way instead of saying that ath.Entrydate is bound to that form, is it possible to set ath.Entrydate automatically in my Functions@{}?

Accepted Answer

In addition, if you're using at least C# 6.0, you can default the initialization value of the property.

public DateTime EntryDate { get; } = DateTime.Now;

Popular Answer

Create a default constructor for EventAthlete and set the entryDate property to today's date.

public class EventAthlete
{
    public DateTime entryDate { get; set; }
    public EventAthlete() => entryDate = DateTime.Now;
}



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why