3
votes

I'm working on a simple website to try out some Blazor (I'm a rookie). I have created a binding with a string value "08:00" and bind i to a input field as shown:

<input @bind-value="@StartValue" @bind-value:event="onchange" class="col-sm-1" type="time"/>
@code {
public string StartValue { get; set; } = "08:00";
}

This generates the error "cannot convert from 'string' to 'System.DateTime'". However, when I remove my binding and create my input as following: it works fine.

<input value="08:00" class="col-sm-1" type="time"/>

Any idéeas why there's a difference? It doesn't make sense to me to use a DateTime, I would agree if I could use a TimeSpan but that doesn't work either.

2
have you tried using bind instead of bind-value ? - Ehsan Sajjad
It seems to return the same error. - JTemnell

2 Answers

1
votes

With @bind-value, you are binding to a string-type, which won't work with type="time".

With value, you entered a correct type "time", and not a string. When you would enter a string like 'foo', it will not work.

1
votes

I tried input type time with TimeSpan and got the following compilation error: Error CS1503 Argument 1: cannot convert from 'System.TimeSpan' to 'System.DateTime'

Blazor maps certain types of <input /> to certain types of CLR types. The reason for this could be to reduce unwanted type and conversion errors, miss behaviors (?).

In the official docs of Blazor this is mentionet in "pieces" like:

When the component is rendered, the value of the input element comes from the CurrentValue property. When the user types in the text box and changes element focus, the onchange event is fired and the CurrentValue property is set to the changed value. In reality, the code generation is more complex because @bind handles cases where type conversions are performed. In principle, @bind associates the current value of an expression with a value attribute and handles changes using the registered handler.

Link to the doc

You could use DateTime and provide a formater like:

<input @bind="StartDate" @bind:format="yyyy-MM-dd" />

@code {
    [Parameter]
    public DateTime StartDate { get; set; } = new DateTime(2020, 1, 1);
}