【问题标题】:How to insert data into multiple tables in ASP. NET MVC. Entity Framework如何在 ASP 中将数据插入到多个表中。网络 MVC。实体框架
【发布时间】:2017-03-27 18:04:34
【问题描述】:

我有两张桌子tblProducttblImagestblImages 将有一个产品的多个图像,并且有一个与 tblProduct 相关的外键。我在将数据插入多个表时遇到问题。

这是我的视图代码:

<!-- Text Boxes and dropdown lists for tblProduct above and below is for adding files to tblImages-->
<div class="col-md-10">
    <input multiple type="file" id="file" name="file" />
</div>

这是我的控制器的代码:

public ActionResult AddProduct_Post([Bind(Include = "productName, productDescription, productPrice, productCategory")]tblProduct tblProduct,List<HttpPostedFileBase> file)
{
    List<tblImage> prodImages = new List<tblImage>();
    var path = "";

    foreach (var item in file)
    {
        if (item != null)
        {
            tblImage img = new tblImage();
            img.ImageFile = new byte[item.ContentLength];
            img.ImageName = string.Format(@"{0}.JPG", Guid.NewGuid());
            img.vend_ID = Convert.ToInt32(Session["userID"]);

            item.InputStream.Read(img.ImageFile, 0, item.ContentLength);

            path = Path.Combine(Server.MapPath("~/Content/img"), img.ImageName);
            item.SaveAs(path);
            prodImages.Add(img);
        }
   }

   tblProduct.venodrID = Convert.ToInt32(Session["userID"]);
   tblProduct.tblImages = prodImages;

   if (ModelState.IsValid)
   {
       db.tblProducts.Add(tblProduct);
       db.SaveChanges();

       int latestProdID = tblProduct.productID;

       foreach (tblImage tblImg in tblProduct.tblImages)
       {
           tblImg.prod_ID = latestProdID;
           db.Entry(tblImg).State = EntityState.Modified;
       }

       db.SaveChanges();

       return RedirectToAction("DashBoard");
   }

   ViewBag.productCategory = new SelectList(db.tblCategories, "categoryID", "categoryName");
   ViewBag.vendorGender = new SelectList(db.tblGenders, "genderId", "genderName");

   return View();
}

我在ModelState.IsValid 上放了一个断点,它没有进入 if 条件,而是返回相同的视图而不发布数据。请告诉我如何解决这个问题

P.S:我是 ASP.NET MVC 的新手

【问题讨论】:

  • 所以你真的没有关于保存数据或实体框架的问题,你只是想找出为什么ModelState.IsValid在这一点上是假的?
  • 使用此答案中提到的代码找出 ModelState.IsValid 返回 false 的原因。 How to figure out which key of ModelState has error.

标签: c# asp.net sql-server asp.net-mvc entity-framework


【解决方案1】:

[Bind(Include =

您可以在操作方法中绑定的检查参数与您在视图中定义的类似,否则您可以删除绑定属性并尝试这将帮助您找到实际错误是什么..

【讨论】:

    猜你喜欢
    • 2016-11-08
    • 1970-01-01
    • 2011-01-04
    • 1970-01-01
    • 2014-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多