I am trying to pass an object to the MVC controller, but at controller, I get null values to the object which I passed through the ajax.
I am able to see that my object is having some data in the view, but not able to bind them to the controller.
Controller
[HttpPost]
public ActionResult AddImage(ImageModel imageModel)
{
UploadRepo.saveImage(imageModel);
return null;
}
Model
namespace Fileupload.Models
{
public class ImageModel
{
public int Id { get; set; }
public string ImageData { get; set; }
}
}
My Javscript Code
var url = input.value;
var imageData = '';
var finalUrL = '';
console.log(input.files[0])
var ext = url.substring(url.lastIndexOf('.') + 1).toLowerCase();
if (input.files && input.files[0] && (ext == "gif" || ext == "png" || ext == "jpeg" || ext == "jpg")) {
finalUrL = await readAsDataURL(input.files[0])
imageData = finalUrL.replace(/^data:image\/[a-z]+;base64,/, '').trim()
var obj = {
Id: 1,
ImageData: imageData
}
$.ajax({
url: '/Upload/AddImage',
type: "POST",
data: JSON.stringify(obj),
contentType: "application/json;",
success: function (data) {
//successMessage();
$("form")[0].reset();
},
error: function (xhr, textStatus, errorThrown) {
console.log("textstatus", textStatus, xhr)
// errorMessage();-
}
});
console.log("imagedata", myobj);
} else {
$('#img').attr('src', '/assets/no_preview.png');
}
}
Attachment file in ASP.NET MVC must be of HttpPostedFileBase type. So, change your image data property as follow i.e.
public HttpPostedFileBase ImageData { get; set; }
then in your [HttpPost] method do following to get data from the uploaded file i.e.
// Upload File data.
byte[] fileByteData = new byte[model.ImageData.InputStream.Length];
model.ImageData.InputStream.Read(fileByteData, 0, fileByteData.Length);
string fileContentType = model.ImageData.ContentType;