Search code examples
c#jsonasp.net-mvchttp-postasp.net-ajax

Using AJAX to post to ASP.NET C# controller


I am trying to send a JSON object like so (I copied the object from the console, and I know the format is off a little) from the view to the controller in ASP.NET.

const obj = {
_405: {ratingID: '_8570', pts: '20'}
_2734: {ratingID: '_9791', pts: '20'}
_4041: {ratingID: 'blank', pts: '20'}
_5649: {ratingID: '_2544', pts: '20'}
_8025: {ratingID: '_4411', pts: '20'}
}

Here is my View ajax:

$.ajax({
    type: 'POST',
    url: '@Url.Action("SendGrade", "Faculty")',
    data: obj,
    success: function(result) {
       console.log(result)
    }
})

And here is my controller code:

[HttpPost]
public ActionResult SendGrade(string rubric){
    Console.WriteLine(rubric);
    return null;  
} 

The call is making it to the controller, but the rubric variable is null. I have already looked at other answers and have been trying them for the past two hours with no success. I've tried adding different ajax properties like conentType and dataType but this had no effect. I also tried JSON.stringify on the object. Also, I tried putting JObject instead of string as the type in the controller function, but this was throwing a 500 error. Any help would be greatly appreciated. I'm using ASP.NET 5.


Solution

  • asp.net controller has default behavior to deserialize input data to an object. you input obj is not a string, it's a object which you are trying to map with string in your controller.

    you need to create a class similar to you input structure. I have create a sample code for your reference.

    Input Object

    var obj = [
                { ratingID: '_8570', pts: '20' },
                { ratingID: '_9791', pts: '20' },
                { ratingID: 'blank', pts: '20' },
                { ratingID: '_2544', pts: '20' },
                { ratingID: '_4411', pts: '20' }
            ];
    

    Matching Class for this input

    public class Rubric
            {
                public string RatingId { get; set; }
                public int Pts { get; set; }
            }
    

    Controller

    [HttpPost]
            public IActionResult Index([FromBody]List<Rubric> rubric)
            {
                Console.WriteLine(rubric);
                return NoContent();
            } 
    

    Javascript code for submit

    function send() {
                $.ajax({
                    type: 'POST',
                    url: '@Url.Action("Index", "Email")',
                    contentType: "application/json",
                    data: JSON.stringify(obj) ,
                    success: function(result) {
                        console.log(result);
                    }
                })
            }
    

    This code is only for your reference that will give you an idea to solve your problem.