In controller using HttpPostedFileBase to get file upload
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "MaSP,TenSP,DonViTinh,DonGia,MaNCC,SoLuong,Anh,MoTaSP")] SanPham sanPham, HttpPostedFileBase file)
{
if (ModelState.IsValid)
{
if (file.FileName != null)
{
file.SaveAs(HttpContext.Server.MapPath("~/Images/")
+ file.FileName);
}
db.SanPhams.Add(sanPham);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.MaNCC = new SelectList(db.NhaCungCaps, "MaNCC", "TenNCC", sanPham.MaNCC);
return View(sanPham);
}
In Create.cshtml
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
.....
<div class="form-group">
@Html.LabelFor(model => model.Anh, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
<input id="Anh" title="Upload hình sản phẩm"
type="file" name="file" class="form-control"/>
@Html.ValidationMessageFor(model => model.Anh, "", new { @class = "text-danger" })
</div>
</div>
I clicked a button - viewing this function in controller then it got null HttpPostedFileBase file -> file got null