简体   繁体   中英

upload file in jquery ajax to asp.net, but result json fail

My Steps: step1. upload a file to server step2. server get the file and saved it to the storage step3. server return the result( success or fail ) to client

The program error in the Step3, textStatus = parsererror; readyState: 4

In the client side:

var data = new FormData();
data.append("file", document.getElementById('file').files[0]);
data.append("id",$('#saveClassID').val());                

$.ajax(
       {
           url: uploadFile,
           data: data,  //
           type: 'post',
           async: false,    
           contentType: false,               
           dataType: 'json',
           processData: false,
           success: function (data) {                   
               if (data.status == "OK") {                      
                   alert('success');
               }
               else {
                   alert(fail);
               }
           },
           error: function(jqXHR, textStatus, errorThrown) {
               console.log(textStatus, errorThrown);
           }
       });

In the Server Side:

[HttpPost]
    public ActionResult uploadFile()
    {
        HttpPostedFileBase file = (HttpPostedFileBase)Request.Files["file"];
        int save_id = Convert.ToInt32(Request.Form["id"].ToString());

        Result result = new Result();
        if (file != null)
        {
            if (file.ContentLength > 0)
            {
              //savedata, and get result  public Result saveData(file,id)
                  result = saveData(file,id);           
            }
            else
            {
                    result.msg="error";
                    result.staut="fail";
            }
        else
        {
             result.msg="no file";
            result.status="fail";
        }
        return Json(result, JsonRequestBehavior.AllowGet);

   }

   public class Result
   {
        public string status;
        public string msg;         
   }

I don't know how to modify my code, 1.if I modify the code in the client side, "contentType: false" to json, server side will failed to get "ID", 2.if I modify the code in the server side for testing, "return Json ( return Json(new{status = "OK"}, JsonRequestBehavior.AllowGet);" ,the code still failed

Thank you

Try

return Json(new {result}, JsonRequestBehavior.AllowGet); 

After adding Result properties, not fields (with { get; set; }) as @Stephen Muecke mentioned

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