I am trying to upload an image to save it to SQL Server Express.
This is my view:
@model Nettbutikk.Models.ProductsModel
@{
}
@Html.Raw(ViewBag.msg)
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<h1>Add New Product</h1>
<form enctype="multipart/form-data">
<p>
<span>Product price<label>*</label></span>
<br />
@Html.EditorFor(ProductsModel => ProductsModel.ProductPrice, new { @htmlattributes = new { @class = "control-form" } })
</p>
<p>
<span>Image<label>*</label></span>
<br />
@Html.TextBoxFor(ProductsModel => ProductsModel.ProductImage, new { type = "file" })
</p>
<p>
<input type="submit" value="Add New Product" />
</p>
</form>
}
Here is my model class:
public class ProductsModel
{
public Image ProductImage { get; set; }
public int ProductPrice { get; set; }
public int ProductId { get; set; }
}
And this is my controller method:
[HttpPost]
public IActionResult NewProduct(ProductsModel objProductModel)
{
string conStr = "Data Source=.\\SQLEXPRESS; Initial Catalog=Nettbutikk; Integrated Security=True";
SqlConnection con = new SqlConnection(conStr);
con.Open();
string query = "insert into products(price, picture) select " + objProductModel.ProductPrice + ", BulkColumn FROM Openrowset(Bulk '" + objProductModel.ProductImage + "', Single_Blob) as img";
SqlCommand cmd = new SqlCommand(query, con);
cmd.ExecuteNonQuery();
con.Close();
return View();
}
The problem is that objProductModel.ProductImage is null, which means the image is not sent to the controller. What am I doing wrong? Please help.
Imagein your model is not correct, and you need to addenctype="multipart/form-datato@using (Html.BeginForm()), and then get rid of the second form inside that form. Inspect the rendered HTML and you'll see that Html.BeginForm creates a form tag.ProductImageis null / empty, you'll know there's a problem on your view / form. I've always used a regular HTML input tag with thetype="file"attribute. If you do that, be sure to also include thenameattribute so MVC maps it to your model property. The question in the thread linked above shows how the OP of that question has their input form field defined for the file upload