我想做一个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);
}
某些东西与您显示的代码不符。在声明'photo = new Photo()'之前,你需要调用'photo.SaveImage(..)',以便引发异常。由于'SaveImage()'设置'ProfileImagePath'属性的值,为什么使用'ProfileImagePath = filePathToSave'重新设置它(不同的值)? –