Ajax call returns null data, but object is not null

NoPatch4HumanSociety 21 Reputation points
2022-05-26T10:41:42.207+00:00

Hi, I've a problem:
I've a javascript in a .cshtml which contains an ajax post call:

var toExportInPDF = @Html.Raw(Json.Serialize(@Model.DetailsInfoToExport.ToList()));  
console.log(toExportInPDF); //this is not null (array with 2888 records)  
        $.ajax({  
            type: "POST",  
            url: "@Url.Action(nameof(MyController.PostDetails), MvcUtils.GetControllerName(nameof(MyController)))",  
            data: { list: toExportInPDF },  
            dataType: "json"  
        }).done(function (data) {  
            const elements = JSON.parse(data);  
            console.log(data); //this is null  

in MyController.cs, I've:

 [HttpPost]  
        public ActionResult PostDetails(List<InfoToExport> list)  
        {  
            var x = list;  
            return new JsonResult(JsonConvert.SerializeObject(x));  
        }  

@默 .DetailsInfoToExport is a List<InfoToExport> and I'm sure that it is not null.

InfoToExport is:

public class InfoToExport  
    {  
        public string Product { get; set; } = string.Empty;  
        public string Version { get; set; } = string.Empty;  
        public string Vendor { get; set; } = string.Empty;  
    }  

DetailAnalisysModel is:

public class DetailAnalisysModel  
     {  
         public List<InfoToExport> DetailsInfoToExport { get; set; } = new List<InfoToExport>();  
     }  

But the ajax POST call, returns data null.

Can someone tell me why? I've tried so many ways, but data is still null.

Thank you

PS: my code works on other pages (in <script> section - Javascript), but not here.

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,178 questions
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,263 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,267 questions
0 comments No comments
{count} votes

Accepted answer
  1. AgaveJoe 26,136 Reputation points
    2022-05-26T13:58:22.807+00:00

    Example

    namespace MvcBasic.Controllers
    {
        public class AjaxController : Controller
        {
            [HttpGet]
            public IActionResult Index()
            {
                var data = new DetailAnalisysModel()
                {
                    DetailsInfoToExport = new List<InfoToExport>()
                    {
                        new InfoToExport()
                        {
                            Product = "Widget 1",
                            Vendor = "Vendor 1",
                            Version = "1"
                        },
                        new InfoToExport()
                        {
                            Product = "Widget 2",
                            Vendor = "Vendor 2",
                            Version = "1"
                        }
                    }
            };
                return View(data);
            }
    
            [HttpPost]
            public IActionResult Index([FromBody] List<InfoToExport> list)
            {
                return Ok(list);
            }
        }
        public class DetailAnalisysModel
        {
            public List<InfoToExport> DetailsInfoToExport { get; set; } = new List<InfoToExport>();
        }
        public class InfoToExport
        {
             public string Product { get; set; } = String.Empty;
    
            public string Version { get; set; } = String.Empty;
    
            public string Vendor { get; set; } = String.Empty;
        }
    
    }
    

    Script

        var toExportInPDF = @Html.Raw(Json.Serialize(@Model.DetailsInfoToExport.ToList()));
        console.log(JSON.stringify(toExportInPDF)); 
    
    $.ajax({
        type: "POST",
        url: "/Ajax/Index",
        data: JSON.stringify(toExportInPDF),
        contentType: 'application/json',
        dataType: "json"
    }).done(function(data) {
        console.log(data); 
    });
    

2 additional answers

Sort by: Most helpful
  1. AgaveJoe 26,136 Reputation points
    2022-05-26T11:06:55.053+00:00

    The JSON format does not match the C# object model structure. The action expects a list of InfoToExport but the client passes the list within another object named list. You should be able to simply change the AJAX data property as below.

    data: toExportInPDF,
    

    If you want to wrap the collection in an object then update the object model and action parameter.

    public class MyModel
    {
        public List<InfoToExport> InfoToExport {get; set;} 
    }
    public class InfoToExport
    {
        public string Product { get; set; } = string.Empty;
        public string Version { get; set; } = string.Empty;
        public string Vendor { get; set; } = string.Empty;
    }
    

    ...

    public ActionResult PostDetails(MyModel list)
    

  2. Albert Kallal 4,651 Reputation points
    2022-05-26T18:12:25.137+00:00

    When you call a web method, the result is data.d

    This is a long time quirk of asp.net

    So, this code:

    const elements = JSON.parse(data);

    should become this:

    const elements = JSON.parse(data.d);

    The returned "payload" does come back as data in above, but the actual result is data.d, and that .d is where the actual data from the web method will be found. This is even the case for a raw file or whatever.

    0 comments No comments