I am using following code to pass file object via JSON to MVC Controller along with data object.
The data object is being catched by MVC Controller method but file always pass as null (JSON object successfully contains file).
Form is not getting submitted. But, calling 'INSETPART' javascript method on save button click. From javascript method,ajax call is initiated.
I want to send html page data along with uploaded file to the controller method.
HTML :
<input name="Image" class="form-control" placeholder="Image" maxlength="50" type="file" accept="image/*" id="txtImage" required="required" />
JSON :
function InsertPart() {
product = {
PartName: $("#txtPartName").val(),
AutoexelPartNo: $("#txtAutoexelPartNo").val(),
Description: $("#txtDescription").val(),
Price: $("#txtPrice").val(),
ImageUrl: $('input[type=file]').val(),
MakeId: $("#MakeDetails").val(),
SubCategoryId: $("#SubCategoryDetails").val(),
PartMasterOEMDetails: OEMDetails,
PartMasterMappedWithOthers: CrossReferences
}
var formData = new FormData();
var image = $('input[type=file]')[0].files[0];
var url = '@Url.Action("InsertProduct", "Admin")';
$.ajax({
contentType: 'application/json;cjarset=utf-8',
dataType: 'json',
type: "POST",
url: url,
data: JSON.stringify({ imagefile: image, part: product }),
async: false,
success: function (data) {
$('#divMessage').html(data);
},
error: function (response) {
}
});
}
MVC Controller:
public ActionResult InsertProduct(HttpPostedFileBase imagefile, PartMaster part)
{
string Message;
bool Successful;
ProductAdminBusiness ba = new ProductAdminBusiness();
Successful = ba.InsertPartMaster(part);
if (Successful)
{
HttpPostedFileBase myFile = imagefile;
bool isUploaded = false;
string message = "";
if (myFile != null && myFile.ContentLength != 0)
{
string pathForSaving = Server.MapPath("~/Content/Store/Products");
try
{
myFile.SaveAs(Path.Combine(pathForSaving, myFile.FileName));
isUploaded = true;
}
catch (Exception ex)
{
message = string.Format("File upload failed: {0}", ex.Message);
}
}
Message = "Product added successfully";
}
else
{
Message = "Unable to add product";
}
return Json(Message, MediaTypeNames.Text.Plain);
}