2015-10-19 84 views
0

我想做一个foreach循环,正在采取所有的形象,当我调试代码,我可以看到它需要图像corect但不是所有的数据库。如果我选择3张图像,则只有2个来自数据库,而第三个只有路径,而不是图像。问题与foreach循环通过图像

有人可以帮助我。

这是我在我的照片型号代码:

public class Photo 
{ 
    public int PhotoId { get; set; } 

    public String ProfileImagePath { get; set; } 

    public int StudentId { get; set; } 

    public virtual Student Student { get; set; } 

    public void SaveImage(HttpPostedFileBase image, 
     String serverPath, String pathToFile) 
    { 
     if (image == null) return; 

     string filename = Guid.NewGuid().ToString(); 
     ImageModel.ResizeAndSave(
      serverPath + pathToFile, filename, 
      image.InputStream, 200); 

     ProfileImagePath = pathToFile + filename + 
     ".jpg"; 
    } 


} 

这里是我的控制器代码:

[HttpPost] 
    [ValidateAntiForgeryToken] 
    public ActionResult Create([Bind(Include = "StudentId,Name,Adress")] Student student, 
     HttpPostedFileBase[] image) 
    { 
     if (ModelState.IsValid) 
     { 


      foreach (HttpPostedFileBase file in image) 
      { 

       string filePathToSave = "/ProfileImages/"; 
       photo.SaveImage(file, HttpContext.Server.MapPath("~"), "/ProfileImages/"); 
       photo = new Photo 
       { 
        StudentId = student.StudentId, 
        Student = student, 
        ProfileImagePath = filePathToSave 
       }; 
       db.Photos.Add(photo); 
      } 
      db.Students.Add(student); 
      db.SaveChanges(); 
      return RedirectToAction("Index"); 
     } 

     return View(student); 
    } 
+1

某些东西与您显示的代码不符。在声明'photo = new Photo()'之前,你需要调用'photo.SaveImage(..)',以便引发异常。由于'SaveImage()'设置'ProfileImagePath'属性的值,为什么使用'ProfileImagePath = filePathToSave'重新设置它(不同的值)? –

回答

2

您还没有表现出正确的代码(您已经表明将抛出一个异常什么)所以我想你一定已经宣布了

Photo photo = new Photo(); 

之前的某个地方photo.SaveImage(..)该行很可能成为错误的根源。此外,您photo.SaveImage()ProfileImagePath值(说.../ProfileImages/someGuid.jpg),但是你覆盖它,并与刚刚/ProfileImages/当你调用ProfileImagePath = filePathToSave

更改您的代码

var path = HttpContext.Server.MapPath("~/ProfileImages"); // only need to set this once 
foreach (HttpPostedFileBase file in image) 
{ 
    Photo photo = new Photo 
    { 
     StudentId = student.StudentId, // no need to set the Student property 
    }; 
    photo.SaveImage(file, path); // this will set the ProfileImagePath property 
    db.Photos.Add(photo); 
} 

SaveImage()方法来代替它

public void SaveImage(HttpPostedFileBase image, string path) 
{ 
    if (image == null) return; 
    string filename = string.Format("{0}.jpg", Guid.NewGuid()); 
    // not sure what the following line does to it may also need to be modified? 
    ImageModel.ResizeAndSave(path, filename, image.InputStream, 200); 
    ProfileImagePath = Path.Combine(path, filename); 
} 

不过我会考虑移动SaveImage()方法了Photo的类和单独的服务,特别是因为它似乎在另一个类中调用静态方法。

+0

谢谢你的帮助 – tinaw25