MVC ajax将字符串作为[object]对象返回

时间:2017-01-10 02:09:51

标签: jquery ajax asp.net-mvc

这是我的ajax代码,它提交带有文件的formdata。 如果我总是删除我的自定义字符串“has”文件将工作并返回“1234567”。我期望返回有“有文件1234567”但总是抛出[object]对象

 $( document ).ready(function() {
     $('#scan').change(function (e) {
         debugger

         var element = this;
         var formData = new FormData();
         var totalFiles = document.getElementById("scan").files.length;

         var file = document.getElementById("scan").files[0];
         formData.append("scan", file);
         $.ajax({
             url: '@Url.Action("scancode", "Products")',
             type: "POST",
             dataType: "json",
             data: formData,
             processData: false,
             contentType: false,
             success: function (data) {

                 $('#barcode').val(data);                   
             },
             error: function (err) {

                 document.getElementById('emsg').innerHTML = err;
             }
         });
     });
});

控制器

 public string scancode(HttpPostedFileBase scan) {
        var str = "";
        if (scan !=null)
        {
            str = "has file";
        }

        try
        {


        IBarcodeReader reader = new BarcodeReader();
        // load a bitmap
        var barcodeBitmap = (Bitmap)Bitmap.FromStream(scan.InputStream);
        // detect and decode the barcode inside the bitmap
        var result = reader.Decode(barcodeBitmap);
        // do something with the result
        if (result != null)
        {
            str =str+ result.Text;
        }
        }
        catch (Exception ex)
        {

            str = ex.Message;
        }
        return str;
    }

2 个答案:

答案 0 :(得分:1)

您必须始终将JsonResult从控制器返回到ajax查询。只需使用JsonResult

将字符串转换为Json(stringvalue);即可

您的代码将变为:

public JsonResult scancode(HttpPostedFileBase scan) 
{
    var str = "";
    if (scan !=null)
    {   
        str = "has file";
    }
    try
    {
        IBarcodeReader reader = new BarcodeReader();
        // load a bitmap
        var barcodeBitmap = (Bitmap)Bitmap.FromStream(scan.InputStream);
        // detect and decode the barcode inside the bitmap
        var result = reader.Decode(barcodeBitmap);
        // do something with the result
        if (result != null)
        {
            str =str+ result.Text;
        }
    }
    catch (Exception ex)
    {
        str = ex.Message;
    }
    return Json(str);
}

答案 1 :(得分:1)

您实际上无法从ajax调用返回字符串。返回一个JSON对象。 将返回类型更改为JsonResult

public JsonResult scancode(HttpPostedFileBase scan) 

而不是return str;返回Json:

return Json(new { someString = str }); 

最后你的ajax调用应该是这样的:

success: function (data) { $('#barcode').val(data.someString); }