在控制器中 使用HttpPostedFileBase获取文件上传
[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);
}
在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>
我点击了一个按钮 - 在控制器中查看此功能然后它变为空 HttpPostedFileBase文件 - &gt;文件已归零