简体   繁体   中英

Ajax post sending JSON to method resulting null

I can't understand where the issue is.
I have a AJAX call that pass to the controller an object with some file paths to download. This is the AJAX call:

var listD = [];  
listD.push("Some Text");  
listD.push("Some other Text");  
var oList = {};  
oList.Urls=listD;  
                    $.ajax({  
                    method: 'POST',  
                    url: '/api/file/DownloadM/',  
                    data: JSON.stringify(oList),  
                    contentType: "application/json; charset=utf-8",  
                    success: function (response) {  
                        alert("OOOOOOK");  
                    },  
                    error: function (response) {  
                        alert("NOOOOOOO");  
                }  }); 

I have a model called DownloadUrls in my application:

public class DownloadUrl
    {
        string[] Urls { get; set; }
    }

And this is my method:

    [Route("api/file/downloadM/")]//{username}")]
    [HttpPost]
    public HttpResponseMessage DownloadM(DownloadUrl postedData) {
              --do some stuff---
    }

I don't understand why my postedData is an object with Urls property set to null. If i declare postedData as object i get my JSON text.

What am i missing? I'm quite new in web developing and i'll start to destroy the desk with my head.

You should not stringify the object you are passing in the data field in the jquery Ajax call.

Try skipping JSON.stringify():

$.ajax({  
   method: 'POST',  
   url: '/api/file/DownloadM/',  
   data: oList,  
   contentType: "application/json; charset=utf-8",  
   success: function (response) {  
        alert("OOOOOOK");  
   },  
   error: function (response) {  
        alert("NOOOOOOO");  
   }
}); 

Edit: I also notice that the Urls property in your class is not marked as public. Make sure that it's marked as public so the model binder can populate the property successfully.

public class DownloadUrl
{
      public string[] Urls { get; set; }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM