Home > Enterprise >  Using AJAX to post to ASP.NET C# controller
Using AJAX to post to ASP.NET C# controller

Time:02-18

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.

CodePudding user response:

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.

CodePudding user response:

You are sending an object through AJAX. So, in controller action method you can't pass string variable as you did (here) public ActionResult SendGrade(string rubric). Because you are sending an object to action method. You should create a class like this below :

public class Rubric
        {
            public string ratingId { get; set; }
            public string pts { get; set; }     // as you are passing pts as string
        }

and By doing this, Now you can pass this class as Action Method's parameter like this :

public ActionResult SendGrade(Rubric object)

Now, one last change is, you should write data parameter of AJAX as below :

$.ajax({
    type: 'POST',
    url: '@Url.Action("SendGrade", "Faculty")',
    data: {object : obj},     // the only change you should do in AJAX, as naming rule denotes and you are collecting 'object' in action method.
    success: function(result) {
       console.log(result)
    }
})

By doing so, you are supposed to get values in the controller action method.

Note: The variable which we declare in the action method while passing it, must be the same as AJAX data parameter. That's why data : { object : obj } is written in AJAX.

  • Related