在MVC 5中编辑属性

时间:2018-05-03 06:20:09

标签: asp.net-mvc

我想编辑数据库的一些属性但有问题 这是代码控制器

  [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit([Bind(Include = "Product_ID,Product_Name,Product_Price,Product_Date,Product_Image," +
        "Product_Description,Product_Discount,Category_ID,Supply_ID")] Product product, HttpPostedFileBase photo)
    {
        if (ModelState.IsValid)
        {
            if (photo != null)
            {
                if (!isValidContentType(photo.ContentType))
                {
                    ViewBag.Error = "Error";
                    return View();
                }
                else
                {
                    var fileName = new FileInfo(photo.FileName);
                    photo.SaveAs(Server.MapPath("~/Images/" + fileName));
                    product.Product_Image = photo.FileName;
                }
            }
            else
                return RedirectToAction("Index");

            db.Entry(product).State = EntityState.Modified;
            db.SaveChanges();
             return RedirectToAction("Index");             
        }  
        ViewBag.Category_ID = new SelectList(db.Categories, "Category_ID", "Category_Name", product.Category_ID);
        ViewBag.Supply_ID = new SelectList(db.Supplies, "Supply_ID", "Supply_Name", "Supply_Address");

         return View(product);
    }

我希望当我不改变图片时。其他属性仍在改变。 这个代码现在,当我不更改图像和其他属性仍然没有改变。 请帮我解决。感谢

1 个答案:

答案 0 :(得分:0)

解决方案,试一试:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Product_ID,Product_Name,Product_Price,Product_Date,Product_Image," +
    "Product_Description,Product_Discount,Category_ID,Supply_ID")] Product product, HttpPostedFileBase photo)
{
    if (ModelState.IsValid)
    {
        if (photo != null)
        {
            if (!isValidContentType(photo.ContentType))
            {
                ViewBag.Error = "Error";
                return View();
            }
            else
            {
                var fileName = new FileInfo(photo.FileName);
                photo.SaveAs(Server.MapPath("~/Images/" + fileName));
                product.Product_Image = photo.FileName;
            }
        }          

        db.Entry(product).State = EntityState.Modified;
        db.SaveChanges();
         return RedirectToAction("Index");             
    }  
    ViewBag.Category_ID = new SelectList(db.Categories, "Category_ID", "Category_Name", product.Category_ID);
    ViewBag.Supply_ID = new SelectList(db.Supplies, "Supply_ID", "Supply_Name", "Supply_Address");

     return View(product);
}