Bluestreak22
Bluestreak22

Reputation: 144

Setting form value to C# Variable

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@{}?

Upvotes: 0

Views: 431

Answers (2)

L0uis
L0uis

Reputation: 721

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;
}

Upvotes: 1

William Lee
William Lee

Reputation: 81

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;

Upvotes: 3

Related Questions