'Unable to cast object of type 'System.Text.Json.JsonElement' to type 'System.IConvertible'

After converting my application into .NET Core 3.1 , the FromBody json attribute is not working . So Ichanged into [FromBody] JsonElement model. After changing that how can I get the value from model into variable.

In Javascript

 var model = {
                Employees: EmpIds,
                FromDate: $('#fromDate').val(),
                ToDate: $('#toDate').val(),
                Comment:  $('#comment').val(),
            }
            var url = "/Attendance/BulkUpdate"
            $.ajax({
                type: "POST",
                url: url,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                data: JSON.stringify(model),
                success: function (response) {
                    if (response.success) {
                        ShowResultModalPopup(response.responseText);
                    } else {
                        // DoSomethingElse()
                        ShowErrorModalPopup(response.responseText);
                    }
                },
                failure: function (response) {
                    console.log(response.responseText);
                },
                error: function (response) {
                    console.log(response.responseText);
                }
            });
    
    
        }

In Controller

public IActionResult BulkUpdate([FromBody] JsonElement model)
{
            DateTime fromdate = Convert.ToDateTime(model.GetProperty("FromDate"));// How can I store the value from model variable into datetime
            DateTime todate = Convert.ToDateTime(model.GetProperty("ToDate"));
}

Thanks Pol



Solution 1:[1]

You could change like below:

DateTime fromdate = Convert.ToDateTime(model.GetProperty("FromDate").GetString());
DateTime todate = Convert.ToDateTime(model.GetProperty("ToDate").GetString());

Solution 2:[2]

You can use the built in methods to convert those properties to dates:

public IActionResult BulkUpdate([FromBody] JsonElement model)
{
    var fromdate = model.GetProperty("FromDate").GetDateTime();
    var todate = model.GetProperty("ToDate").GetDateTime();
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Rena
Solution 2 davidfowl