Blazor, how to pass a date to IJSRuntime.InvokeVoidAsync

Viewed 30

I'm building a component, and in the OnAfterRenderAsync I'm trying to invoke some javascript and pass an object, that contains a bunch of members, one of which is a DateTime data type.

protected override async Task OnAfterRenderAsync(bool firstRender)
{
    if (firstRender)
    {
        var parameters = new
        {
            date = DateValue            
        };
        await JSRuntime.InvokeVoidAsync("window.myfunction", _inputReference, parameters);      
    }
}

In my javascript I have tested the data type, and I know it's a string...

window.myfunction = (options) {
    var t = typeof options.date;
    console.log(t);
    
    var d = new Date(options.date);
    console.log(d); 
}

Is there a better way to pass a date? I need to work with the value as a date object, but is this really the best way to convert to a Date object (using new Date())? This approach to conversion seems fragile because it means that the Date objects parsing is assuming the format that the server side used. I don't know if that is vulnerable to regional settings differences between the browser and the server.

1 Answers

It's the same scenario as if you were calling an HTTP endpoint that returns a response that contains a DateTime object. The date object would have to get serialized (usually to JSON) and then deserialized from your client.

Same thing is happening when using JS interop. The date has to be serialized to JSON in order to be passed from C# to JavaScript. JSON is a common data transfer format that can be parsed both from C# and JavaScript. The date gets serialized to an ISO 8601 formatted date string.

Related