0

I have two tables tblProduct & tblImages. tblImages will have multiple images for a product and has a foreign key related to tblProduct. I have a problem with inserting data into multiple tables.

This is my view code:

<!-- 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>

and here is my controller's code:

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();
}

I put a breakpoint on ModelState.IsValid and it is not going inside the if conditions and is returning back the same view without posting the data. Kindly tell me how to solve this issue

P.S: I am new to ASP.NET MVC

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Ammar
  • 33
  • 4
  • 1
    So you really don't have a question about saving data or Entity Framework, you just want to find out why `ModelState.IsValid` is false at this point? – mason Mar 27 '17 at 18:10
  • Use the code mentioned in this answer to figure out why ModelState.IsValid returns false. [How to figure out which key of ModelState has error](http://stackoverflow.com/questions/15296069/how-to-figure-out-which-key-of-modelstate-has-error/15296109#15296109). – Shyju Mar 27 '17 at 18:12

1 Answers1

0

[Bind(Include =

you can the check parameter you bind in action method is similar what you defined in the View else you can remove the bind attribute and try this will help you to find what actually error is..

MMM
  • 3,132
  • 3
  • 20
  • 32