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

Polachan Paily 226 Reputation points
2021-06-11T11:35:31.723+00:00

After converting my application into .NET Framework 3.1 , the [FromBody]Model being showed as null . So Ichanged into [FromBody] JsonElement model. After changing that , all the value can be seen in the variable model. But how can I get the each value from model into separate variable in controller . I want to get the value from Html datefrom column into a datetime variable in controller

In Javascript section

In Script section
 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"));
}
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,522 questions
0 comments No comments
{count} votes

Accepted answer
  1. Bruce (SqlWork.com) 64,396 Reputation points
    2021-06-11T16:54:08.83+00:00

    The getproperty returns, in your example, a jsonElement not a string. Try:

    var  fromdate = Convert.ToDateTime(model.GetProperty("FromDate").GetString()); 
    
    0 comments No comments

2 additional answers

Sort by: Most helpful
  1. Michael Taylor 53,896 Reputation points
    2021-06-11T13:59:42.103+00:00

    ASP.NET Core uses the same model binding approach as ASP.NET so the answer remains the same as before, use a strongly typed model.

    //Guessing based upon your JSON
    public class AttendanceModel
    {   
       //Not clear what this type should be...
       public string Employees { get; set; }
       public DateTime FromDate { get; set; }
       public DateTime ToDate { get; set; }
       public string Comments {get; set; }
    }
    
    [HttpPost]
    public IActionResult BulkUpdate ( [FromBody] AttendanceModel model )
    {
    }
    

    What is different is how model binding works. You should definitely read up on the differences but the core concepts work the same. The biggest problems I see when model properties are not set is casing differences (camel in JS and Pascal in C#) or bad data being sent from JS (this is what the dev tools in the browser are for).

    0 comments No comments

  2. AgaveJoe 28,051 Reputation points
    2021-06-11T14:09:59.477+00:00

    I agree with cooldadtx. You should follow standard model binding patterns outlined in the official docs.

    With that being said, I created an example using your code and the FromDate is passed to the action and model.GetProperty("FromDate") returns the date. There must be other issues with your code that we cannot see. You should be able to figure out what's wrong using the browser's dev tools. Take a look at the the JSON payload and step through the JavaScript. Also don't forget to use the Visual Studio debugger.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.