This is my ajax code which submit a formdata with a file. if i remove always my custom string "has" file which will works and return "1234567".i am expecting to return has "has file 1234567" but always throw [object] 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;
}
});
});
});
Controller
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;
}
public JsonResult scancode(HttpPostedFileBase scan)and instead ofreturn str;return the Json:return Json(new { someString = str });and in your ajax call:success: function (data) { $('#barcode').val(data.someString); }dataType: "json",correct in this case ? I don't think files can be posted via ajax....can someone correct me.dataType: "json", your method should bepublic JsonResult scancode(...)withreturn Json(str);dataType: "json"and your sending back a string with spaces in it which will be interpreted as 3 items (note all it needs to be isreturn Json(str);and keep$('#barcode').val(data);)