Home > Software engineering >  How do you pass a json variable in an MVC controller in C# .net core 3.1
How do you pass a json variable in an MVC controller in C# .net core 3.1

Time:10-21

Have followed a number of tutorials on the net but still getting the same result. Microsofts documentation is so in-depth considering all I want to is in essence send one variable to a controller.

My client side code looks like this:

var obj = { send: 'test' };

    $.ajax({
        url: '/Countries/GetVotes',
        type: 'POST',
        contentType: "application/json",
        data: JSON.stringify(obj),
        success: function (data) {
            if (data === null) {
                // TODO
            } else {
                console.log(data);
            }
        },
        error: function (error) {
            console.log(error);
        }
    }); 

Then the controller would look like this:

[HttpPost]
    public async Task<JsonResult> GetVotes(string send)
    {
        try
        {
            var votes = ctx.Candidates.Where(x => x.Country == send)
                .OrderByDescending(x => x.Votes)
                .ToList();
            
            return Json(votes);

        }
        catch (Exception ex)
        {
            logger.Error(ex);
        }

        return Json("foo");
    }

All standard and used to work in .NET framework 4.7.2, anyone whose done any MVC would be very familiar with this approach.

I've made the decision to try using .net core 3.1. Am hitting all the right breakpoints, the problem I have is the string called "send" is sent to my controller as null.

Anybody know the simplest way to get this working?

CodePudding user response:

What you're passing in is a JSON object

{ send: "test" }

What you're expecting in the request body in the controller is just a string. You could try creating a request object that represents the data structure you're expecting:

public class Request {
    public string send { get; set; }
}

Then you can update your controller method to

public async Task<JsonResult> GetVotes([FromBody]Request request) 

And further access the send property through request.send.

CodePudding user response:

you don't neeed stringify when you are sending string already. And remove content type too. Default would be ok.

So try this

  $.ajax({
        url: '/Countries/GetVotes',
        type: 'POST',
     
        data: obj,
        success: function (data) {
            if (data === null) {
                // TODO
            } else {
                console.log(data);
            }
        },
        error: function (error) {
            console.log(error);
        }
    }); 
  • Related