I want to build an online shopping site for that image has to be uploaded with other data like product name price using ajax and json as return type.
My Contoller :
public JsonResult InsertProduct( Product prdObj)
{
var profile = Request.Files;
string imgname = string.Empty;
string ImageName = string.Empty;
//Following code will check that image is there
//If it will Upload or else it will use Default Image
if (System.Web.HttpContext.Current.Request.Files.AllKeys.Any())
{
var logo = System.Web.HttpContext.Current.Request.Files["file"];
if (logo.ContentLength > 0)
{
var profileName = Path.GetFileName(logo.FileName);
var ext = Path.GetExtension(logo.FileName);
ImageName = profileName;
var comPath = Server.MapPath("~/Images/") + ImageName;
logo.SaveAs(Path.Combine(Server.MapPath("~/Images/"), ImageName));
prdObj.ImagePath = comPath;
// prdObj.Add()
return Json(db.InsertProduct(prdObj.ProductName, prdObj.ImagePath,prdObj.Description,prdObj.Price,prdObj.Category), JsonRequestBehavior.AllowGet);
}
}
else
prdObj.ImagePath = Server.MapPath("~/Images/") + "profile.jpg";
int response = 1;
return Json(response, JsonRequestBehavior.AllowGet);
}
js file:
$(document).ready(function () {
$('#btnAddProduct').click(function () {
var formData = new FormData();
var files = $("#productimage").get(0).files;
formData.append("file", files[0]);
formData.append("ProductName", $('#productname').val());
formData.append("Category", $('#category').val());
formData.append("Price", $('#price').val());
// formData.append("Gender", $("input[name='gender']:checked").val());
formData.append("ImagePath", files[0].name);
formData.append("Description", $('#detail').val());
$.ajax({
type: 'POST',
url: "/Admin/InsertProduct",
data: formData,
cache: false,
contentType: false,
processData: false,
success: function (response) {
if (response == 1) {
alert("successfully added");
}
else {
alert("Something Went Wrong..");
}
}
})
})
})
View: