ASP.Net Core AJAX Post Object to MVC Controller Easily

ajax post

To perform an AJAX POST to an ASP Net MVC controller, first, we need to create a JSON object to send back to the controller. We’ll build an object named dataObject as follows:

var dataObject = JSON.stringify({ 
    'FieldA': fieldAArray.join(), 
    'FieldB': fieldBArray.join(), 
    'FieldC': fieldCArray.join() 
});

Note: I am uploading three arrays as strings in this example. For each array, I am joining the elements separated by a comma (just for something different). That means we’ll need three strings in our data model on the server side to store this data.

Create the AJAX Post command

Next, we’ll configure a jQuery AJAX request to send the data to the controller. Once the request is complete, we’ll update an element with an id of message with the text “JSON Data Sent to Server”.

$.ajax({ 
    url: '/Controller/MyAction/', 
    data: myObject, 
    contentType: 'application/json', 
    type: 'POST', 
    success: function (data) { 
        $('#message').html("JSON Data Sent To Server"); 
    } 
});

Create your model in ASP Net Core

Now we’ll need to have a class that represents the data that the controller is expecting from our web page. We’ll call this ActionRequest and implement with three string fields (A, B and C).

public class ActionRequest 
{ 
    public string FieldA { get; set; } 
    public string FieldB { get; set; } 
    public string FieldC { get; set; } 
}

Create the controller action

Finally we need to implement the controller action itself. As we’re sending data to the controller we’ll use a POST request to handle the AJAX Post and return the Index View.

[HttpPost]
public IActionResult MyAction([FromBody] ActionRequest request) 
{ 
    List<string> fieldAAsList = request.FieldA.Split(',').ToList(); 
    List<string> fieldBAsList = request.FieldB.Split(',').ToList(); 
    List<string> fieldCAsList = request.FieldC.Split(',').ToList(); 
    // Do some work here with your lists 
    // Return to the current view 
    return view("Index"); 
}

Note: I am using the annotation [FromBody] we’re telling ASP .Net Core the location where the action’s parameter value can be found. Using this attribute also means that this is the only place that ASP .Net Core will look for the parameter value when receiving an AJAX POST request.

By default, the parameters are taken from the URI (for simple types like strings, dates etc…). For complex types (like the object we’re posting above) there are various binding sources that can be used, [FromBody] is just one of these.

Here is a good article regarding binding and related information in Asp Net.

Be sure to check out some of my other posts:

Ad Blocker Detected

Our website is made possible by displaying online advertisements to our visitors. Please consider supporting us by disabling your ad blocker.

Refresh