当我尝试添加图像时,MVC 总是 return me null

MVC always return me null when I try to add an image

您好,我有一个 MVC 问题,我需要将图像保存到数据库中的 table,但是当我尝试添加图像时总是给我一个错误 "ImageFile.get return null"

这是我的代码

我的模型

public partial class Inventario
{
    public int IdProduct { get; set; }
    [DisplayName("Product")]
    public string Name_Product { get; set; }
    public Nullable<decimal> Price{ get; set; }
    public Nullable<int> Stock{ get; set; }
    [DisplayName("Category")]
    public Nullable<int> IdCategory { get; set; }
    [DisplayName("Upload Image")]
    public string ImagePath { get; set; }


    public HttpPostedFileBase ImageFile { get; set; }
}

我的观点

@using (Html.BeginForm("Create", "AccionesInventarios", FormMethod.Post, new {enctype = "multipart/form-data" }))

<input type="file" name="ImageFile" required>

我的控制器

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "IdProduct,Name_Product,Price,Stock,IdCategory,ImagePath")] Inventario inventario)
{
    string fileName = Path.GetFileNameWithoutExtension(inventario.ImageFile.FileName);
    string extension = Path.GetExtension(inventario.ImageFile.FileName);
    fileName = fileName + DateTime.Now.ToString("yymmssfff") + extension;
    inventario.ImagePath = "~/Image/" + fileName;
    fileName = Path.Combine(Server.MapPath("~/Image/"), fileName);
    inventario.ImageFile.SaveAs(fileName);

    if (ModelState.IsValid)
    {
        db.Inventarios.Add(inventario);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    return View(inventario);
}

您正在使用 Bind 属性来明确限制模型活页夹将从发布的表单数据映射的属性。您没有包含 ImageFile 属性,因此默认模型活页夹未将其从发布的表单数据中映射出来。

将它添加到“绑定包含”列表中,它将起作用。

public ActionResult Create([Bind(Include = "IdProduct,Name_Product, Price,Stock,
                                            IdCategory,ImageFile")] Inventario inventario)
{  
    // to do : Your existing code
}

一个更松散耦合的解决方案是创建一个具有视图所需属性的视图模型并使用它。这是防止过度发布的最佳方法。在 views/view 层中使用数据访问层中的实体 类 也不是一个好主意。它使它与那些 类 紧密耦合。