Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Blazor binding value to "input date" in one-way

Tags:

c#

blazor

Since Blazor doesn't support stopping event propagation I need one-way binding for an input element with type="date" and with an onchange event handler.

Something like this:

<input type="date" value="@_endDate" format-value="yyyy-MM-dd" onchange="@EndDate_change"/>

But this doesn't work. The page contains datePicker but without any value.

"_endDate" is of type DateTime.

If I use Two-way binding then everything working fine.

<input type="date" bind="@_endDate" format-value="yyyy-MM-dd"/>

Any idea why the first "input" doesn't work? Is there any mistake or is this a bug in blazor? For plain text one-way binding with onchange event works without problems.

Edit1: _endDate contains the current date and is set as DateTime.Now

protected void EndDate_change(UIChangeEventArgs endDateEvent)
{
    _endDate = Convert.ToDateTime(endDateEvent.Value);
    StateHasChanged();
}
like image 614
lukesss Avatar asked Apr 22 '19 14:04

lukesss


2 Answers

To keep both @onchange= and a one way value= use this

value="@someDate.ToString("yyyy-MM-dd")"

The trick is to format as a string yyyy-MM-dd to get one way binding from the value. Formatting differently or simply using the DateTime object fails to show the date inside the date selector.

Example:

<input type="date" value="@knowledge.ActualShortTermDate.ToString("yyyy-MM-dd")" @onchange="@(async (e) => await updateDate(DateTime.Parse(e.Value.ToString())))" />

like image 71
Waleed Al Harthi Avatar answered Nov 04 '22 20:11

Waleed Al Harthi


Since in blazor @bind-Value and @onchange cannot co exists as at now here is the best work around

<InputDate type="date" @bind-Value="@_endDate"/>
@code {
 private DateTime endDate;
public DateTime _endDate
{
    get { return endDate; }
    set
    {
        endDate = value;
        //Do Other tasks ......
        // Eg updateSomething();
    }
}
}
like image 42
Brainykat Dev Avatar answered Nov 04 '22 20:11

Brainykat Dev