-1

I am trying to get ID from a json file in an ASP.NET MVC controller but for some reason it gives me "Object reference not set to an instance of an object." error. JsonFile:

"Id": "1",
"FirstName": "FirstName",
"LastName": "LastName",
"Age": "21",

C# class:

public class User
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
}

ASP.NET MVC controller:

model = UserRepository.GetUserById(User.Id);   // error line
marc_s
  • 675,133
  • 158
  • 1,253
  • 1,388
Kazuma
  • 7
  • 4

1 Answers1

1

First you should change Id and Age to numbers, otherwise the model binder will give you an exception. Something like this:

The JSON value could not be converted to System.Int32. Path: $.Id | LineNumber: 0 | BytePositionInLine: 11 `

Your JSON should now look like this:

{
    "Id": 1,
    "FirstName": "FirstName",
    "LastName": "LastName",
    "Age": 21
}

Then you should add a parameter User user to your action instead of declaring the user variable as property of the controller like you probably did as you said in one of your comments.

You should end up with something along these lines:

[HttpPost]
public string MyAction(User user)
{
    if (user is null)
        return "Bad request :(";

    // Do things with user.

    return $"Id: {user.Id}, First Name: {user.FirstName}, Last Name: {user.LastName}, Age: {user.Age}";
}
Streamline
  • 900
  • 1
  • 15
  • 22