Search code examples
c#jquery.netasp.net-mvc-5jsajaxfileuploader

Ajax File upload in Jquery returns success as result


I know this sounds silly but I am stuck as what ever value that is returned using the controller as Json, i.e 1, 0, true or false and on checking the ajax file upload success part data it contains only "Success" as value no matter what the return value of the controller is.

Here, I am using Ajax file upload as I am uploading a file from the client side.

Controller code:

public ActionResult ImportExcelData(HttpPostedFileBase UploadExcel)
{
  try
    {
        var Data = Repository.ImportData(filePath, OrgID);
        return Json(true, JsonRequestBehavior.AllowGet); 
    }
    catch(Exception)
    {
        return Json("false", JsonRequestBehavior.AllowGet);
    }
}

View code:

$.ajaxFileUpload({
    url: '@Url.Action("ImportData", "Lead")',
    secureuri: false,
    type: 'POST',
    datatype: 'JSON',
    contentType: "application/json; charset=utf-8",
    cache: false,
    fileElementId: "Upload",
    success: function (data) {
   //data contains only success as value.
  }
});

Can anybody help me out, cheers.


Solution

  • Finally solved it, when you return the result from the controller instead of returning the JSON I used the "Content(Value)".

    Controller Code:

        public ActionResult ImportExcelData(HttpPostedFileBase UploadExcel)
         {
          try
            {
             var Data = Repository.ImportData(filePath, OrgID);
             if(sData!=null)
                {
                    string sJSON = String.Join(",", sData);
                    return Content(sJSON);
                }
                else
                {
                    return null;
                }
            }
          catch(Exception)
           {
             return Json("false", JsonRequestBehavior.AllowGet);
           }
          }
    

    In the ajax file upload success part, instead of using the one string to get the data use two strings where the second string has the values returned. This may be because of some problem with the ajax file upload plugin.

    View Code:

        $.ajaxFileUpload({
         url: '@Url.Action("ImportData", "Lead")',
         secureuri: false,
         type: 'POST',
         datatype: 'JSON',
         contentType: "application/json; charset=utf-8",
         cache: false,
         fileElementId: "Upload",
         success: function (data,result) {
         //"result contains your values.
        }
       });