Here is my model:
public int DiscountAvailable { get; set; }
public string Color { get; set; }
public string Size { get; set; }
public int Stock { get; set; }
public String Other1 { get; set; }
public string Other2 { get; set; }
public byte[] Image { get; set; }
Here is my controller:
public JsonResult Add(Products Product)
{
return Json(ProductDB.Add(Product), JsonRequestBehavior.AllowGet);
}
Here is my ADO to connect with database:
int i;
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand cmd = new SqlCommand();
string query = "Insert into Products (CategoryId, SubCategoryId, DiscountAvailable, Stock, Color, Size, Other1, Other2) values(@CatId, @SubCatId, @Sto, @Col, @Siz, @Oth1, @Oth2)";
cmd.CommandText = query;
cmd.Connection = con;
cmd.Parameters.AddWithValue("@CatId", Product.CategoryId);
cmd.Parameters.AddWithValue("@SubCatId", Product.SubCategoryId);
cmd.Parameters.AddWithValue("@SuppId", Product.SupplierId);
cmd.Parameters.AddWithValue("@ProdN", Product.ProductName);
cmd.Parameters.AddWithValue("@Pur", Product.PurchasePrice);
cmd.Parameters.AddWithValue("@Ima", Product.Image);
i = cmd.ExecuteNonQuery();
}
return i;
Here is my ajax:
function Add() {
var res = validate();
if (res === false) {
alert("nOT VALID");
return false;
}
var file_data = $('#Image').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
console.log("Here");
var ProductObj = {
CategoryId: $('#CategoryId').val(),
SubCategoryId: $('#SubCategoryId').val(),
Stock: $('#Stock').val(),
Color: $('#Color').val(),
Size: $('#Size').val(),
Other1: $('#Other1').val(),
Other2: $('#Other2').val(),
Image: file_data,
};
console.log(ProductObj);
$.ajax({
url: "/Products/Add",
data: JSON.stringify(ProductObj),
type: "POST",
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (result) {
loadData();
console.log(result);
$('#myModal').modal('hide');
},
error: function (errormessage) {
alert(errormessage.responseText);
}
});
}
I have created a .cshtml and inside that there is input field with type 'file'. Ajax calls controller and controller calls DB from which data is inserted to the database. Inside the database I have defined the image
column as type 'varbinary(MAX)'.
My question is: what should I do in controller to handle the image? And what changes should be made in the model?