Ibrahim Shaikh
Ibrahim Shaikh

Reputation: 398

List is appearing to be null when calling from AJAX

I am creating a web app in which I have a scenario where I am sending data in list in the back-end, the below example explains this,

My Modal

public class NavigationModal
{
    public int regId { get; set; }
    public string URL { get; set; }
}

My Function

    public int postData(List<NavigationModal> contents)
    {
        Session["data"] = contents;
        return 1;
    }

My Controller Name

public class NavigationController : Controller

Code in front end

var data = [];

function StoreDataInSession(regId, MyRegistrations) {
    var contents = {
        regId: regId,
        URL: window.location.pathname.split("/")[2] == null ? 'index' : window.location.pathname.split("/")[2]
    };
    data.push(contents);
    var newData = JSON.stringify({ 'contents': data });
    $.ajax({
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        type: 'POST',
        url: '../Navigation/postData',
        data: data,
        success: function () { ReDirectToAction(); }
    });
}

But my data is appearing to be null when I am debugging my controller, and when I see the data in console, it is coming properly.

What is my issue?

enter image description here

Upvotes: 0

Views: 49

Answers (1)

Tetsuya Yamamoto
Tetsuya Yamamoto

Reputation: 24957

Sounds like your action method has wrong return type and HTTP method in this definition:

public int postData(List<NavigationModal> contents)

Note that a controller which receives JSON data from AJAX request must have at least ActionResult as return type (you can use JsonResult as alternative because of dataType: json setting) and specify [HttpPost] attribute because type: POST has been set in AJAX callback.

The correct setup for AJAX request should be like this example below:

Controller Action

[HttpPost]
public JsonResult PostData(List<NavigationModal> contents)
{
    Session["data"] = contents;
    return Json("true");
}

AJAX callback

var data = [];

function StoreDataInSession(regId, MyRegistrations) {
    var contents = {
        regId: regId,
        URL: window.location.pathname.split("/")[2] == null ? 'index' : window.location.pathname.split("/")[2]
    };
    data.push(contents);
    var newData = JSON.stringify({ 'contents': data });

    $.ajax({
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        type: 'POST',
        url: '@Url.Action("PostData", "Navigation")',
        data: newData,
        success: function () { ReDirectToAction(); }
    });
}

Upvotes: 1

Related Questions