【问题标题】:How to Update Image path and save it back to database如何更新图像路径并将其保存回数据库
【发布时间】:2015-12-21 16:11:51
【问题描述】:

在这里我添加产品并保存图像路径,一切正常并保存图像路径

public ActionResult AddProduct(Product p, HttpPostedFileBase prodImg, decimal[] price)
                    {
                        try
                        {
                            string absoluthFolderPath = Server.MapPath("\\Images");
                            string pathOfImage = System.IO.Path.GetExtension(prodImg.FileName);
                            string newFileName = Guid.NewGuid() + pathOfImage;
                            absoluthFolderPath += "\\" + newFileName;
                            prodImg.SaveAs(absoluthFolderPath);

                            string relitivePath = @"\Images\" + newFileName;
                            p.ImagePath = relitivePath;
                            p.Blocked = false;
                            new ProductsBL().AddProduct(p);
                            ViewData\["msg"\] = "Successfuly";
                        }
                        catch(Exception ex)
                        {

                        }
                        ModelState.Clear();
                        return View();
                    }

当尝试更新图像路径时,屏幕截图中显示错误

 public ActionResult Update(Product modifieDetails, HttpPostedFileBase updImg)
            {
                string absoluthFolderPath = Server.MapPath("\\Images");
                string pathOfImage = System.IO.Path.GetExtension(updImg.FileName);
                string newFileName = Guid.NewGuid() + pathOfImage;
                absoluthFolderPath += "\\" + newFileName;
                updImg.SaveAs(absoluthFolderPath);

                string relitivePath = @"\Images\" + newFileName;
                modifieDetails.ImagePath = relitivePath;
                modifieDetails.Blocked = false;
                new ProductsBL().UpdateProduct(modifieDetails);
                return RedirectToAction("ListProduct");
            }

[1]: http://i.stack.imgur.com/wgE88.png

【问题讨论】:

  • 欢迎来到 SO!请对我们的问题更具体一点。你期望会发生什么?是否有任何错误消息?
  • 问题说他想更新它并将其保存回数据库,这有什么令人困惑的? IMO,这个问题很好。

标签: c# visual-studio model-view-controller


【解决方案1】:

你需要把它分开:

 new ProductsBL().AddProduct(p);

为了将实体的更新保存回商店,您必须在实体上设置“IsModified”,然后保存上下文。就这样……

using (ProductsBL context = new ProductsBL()) {
    var p = (some query to get it from the store);
    p.ImagePath = relitivePath;
    p.Blocked = false;
    p.IsModified = true;
    context.SaveChanges();
}

事实上,您正在创建一个新实体并将其添加到商店,而不是更新现有实体。

而且,如果您使用英文编码,请修正拼写:Modify、Relative、absolute。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-07
    • 2012-07-26
    • 1970-01-01
    • 1970-01-01
    • 2014-06-07
    • 1970-01-01
    • 2012-01-18
    相关资源
    最近更新 更多