c# – 在HttpPost之后更新模型
发布时间:2020-12-16 01:45:08  所属栏目:百科  来源:网络整理 
            导读:我想通过图像更新数据库中的现有Product对象,但只有当我创建新对象时,图像才会成功转到DB. 我试图以这种方式更新我的对象 [HttpPost]public ActionResult Edit(Product product,HttpPostedFileBase image) { if (ModelState.IsValid) { if (image != null) {
                
                
                
            | 
                         
 我想通过图像更新数据库中的现有Product对象,但只有当我创建新对象时,图像才会成功转到DB. 
  
  
我试图以这种方式更新我的对象 [HttpPost]
public ActionResult Edit(Product product,HttpPostedFileBase image)
    {
    if (ModelState.IsValid)
        {
            if (image != null)
            {
                product.ImageMimeType = image.ContentType;
                product.ImageData = new byte[image.ContentLength];
                image.InputStream.Read(product.ImageData,image.ContentLength);
            }
            if (product.ProductID != 0)
                UpdateModel<Product>(repository.Products.FirstOrDefault(p => p.ProductID == product.ProductID));
            repository.SaveProduct(product);
            TempData["message"] = string.Format("{0} has been saved",product.Name);
            return RedirectToAction("Index");
        }
        return View(product);
    }
//repository.SaveProduct()
public void SaveProduct(Product product)
        {
    if (product.ProductID == 0)
            {
                context.Products.Add(product);
            }
            context.SaveChanges();
        } 
 风景 ????@ 解决方法
 这是各种错误的. 
  
  
        您应该使用特定的ViewModel进行编辑和创建操作. 定义一个单独的类,其中包含您要编辑的属性和任何UI验证: public class EditProductViewModel {
    [HiddenInput]
    public int Id {get;set;}
    [Required]
    public string Name {get;set;}
    [Required]
    public string Description {get;set;}
    public HttpPostedFileBase Image {get;set;}
} 
 然后像这样改变你的动作方法: [HttpPost]
public ActionResult Edit(EditProductViewModel viewModel) {
    if (ModelState.IsValid) {
        var product = repository.Products.FirstOrDefault(p => p.Id == viewModel.Id);
        // TODO - null check of product
        // now lefty righty
        product.Name = viewModel.Name;
        product.Description = viewModel.Description;
        if (viewModel.Image.ContentLength > 0) {
            product.ImageMimeType = image.ContentType; //  wouldn't trust this (better to lookup based on file extension)                
            product.ImageData = new byte[image.ContentLength];                 
            image.InputStream.Read(product.ImageData,image.ContentLength); 
        }
        repository.SaveProduct(product);
        return RedirectToAction("Index");
    }
    return View(viewModel);
} 
 Here’s a good post讨论了ViewModel模式. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!  | 
                  
