简体   繁体   中英

How to receive a data from the JSon method?

I have a method in my controller that submits some changes in the database after receiving a filename that being uploaded to the server. Also this method is getting the fileNameOrigin and fileNameUnique (to be downloaded for saving in the server folder)

 public JsonResult Upload()
        {
var upload = Request.Files[file];
string fileNameOrigin = System.IO.Path.GetFileName(upload.FileName);
string fileNameUnique = String.Format("{0}_" + fileNameOrigin,
                        DateTime.Now.ToString("yyyyMMddHHmmss"));
//there is more code that isn't needed in my case
return Json(fileNameOrigin, fileNameUnique);
        }

So, here's the question - how to send and receive this data on the client side?

$('#uploadFile').on('change', function (e) {
            e.preventDefault();
            var files = document.getElementById('uploadFile').files;            
            if (files.length > 0) {
                if (window.FormData !== undefined) {
                    var data = new FormData();
                    for (var x = 0; x < files.length; x++) {
                        data.append("file" + x, files[x]);

                    }

                    $.ajax({
                        type: "POST",
                        url: '@Url.Action("Upload", "ChatRooms")',
                        contentType: false,
                        processData: false,
                        data: data,
                        success: onSuccess, //here I need to receive data and do smth with it
                        error: onError


                    });
                }
            }
        });

Create a anonymous object with the properties that are required and then pass that single object to the JSON method like:

var data = new { 
                  FileNameOrigin = fileNameOrigin, 
                  FileNameUnique = fileNameUnique
               };

return Json(data);

In success callback of ajax, you can access it, for just to check it is working log it on console to see what server has returned like:

success: function(data) {

       console.log(data);
      },

you might also need to specify datatype in ajax call to json which dictates that JSON is expected from server to be returned in response to this ajax call:

dataType: "json"

Hope it helps!

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