How to set datetime property of blazor component in Markup?

Viewed 28

If I have a Blazor Component with a datetime property, How do I set it through the markup? I just get an error cannot convert 'int' to 'datetime?'.

public class MyComponent
{
    [Parameter]
    public DateTime? Value
    {
        get => _value;
        set
        {
            if (_value == value) return;
    
            _value = value;
            ValueChanged.InvokeAsync(Value);
        }
    }
}

In razor page:

<MyComponent Value="2022/01/01"></MyComponent>

Is there way to somehow create an implicit conversion for the property?

2 Answers

If you want to pass the date parameter as a string then you have to change the Value property type to string? and parse it to DateTime? in the setter. (I don't know why someone would want to do that.)

MyComponent.razor:

@code {
    private DateTime? _value;

    [Parameter]
    public string? Value
    {
        get => _value?.ToString("yyyy/MM/dd");
        set
        {
            if (value == null) _value = null;

            if (DateTime.TryParse(value, out var result))
            {
                if (_value == result) return;

                _value = result;
                ValueChanged.InvokeAsync(Value);
            }
        }
    }

    [Parameter]
    public EventCallback<string?> ValueChanged { get; set; }
}

Usage:

<MyComponent Value="@("2022/01/01")"></MyComponent>
<MyComponent Value="new DateTime(2022/01/01)"></MyComponent>

or

<MyComponent Value="dateField"></MyComponent>

@code
{
    private DateTime? dateField = new DateTime(2022/01/01);
}

or to bind the value, so when it changes the field changes too:

<MyComponent @bind-Value="dateField"></MyComponent>
Related