I'm currently facing an issue with handling validation errors in my application. I have implemented uploading and downloading images successfully, but when there are validation errors and the controller redirects back to the page, the HttpPostedFileBase object becomes empty. This means that the user has to re-upload the image, which is less than ideal. Is there a way to reload the image into HttpPostedFileBase without requiring the user to upload it again?
In my controller, I've attempted to set the HttpPostedFileBase back to the returned HttpPostedFileWrapper, but this approach doesn't work on subsequent postbacks. The object remains empty, even after resubmitting the form.
[HttpPost]
public ActionResult Edit(EditStudentViewModel studentViewModel)
{
if (ModelState.IsValid)
{
//do stuff here
} else
{
var years = Enumerable.Range(DateTime.Now.Year - 99, 100).Reverse();
studentViewModel.Years = years.Select(c => new SelectListItem
{
Text = c.ToString(),
Value = c.ToString(),
Selected = (c == studentViewModel.SelectedYearId)
});
studentViewModel.StudentImageResult =
new FileContentResult(
System.IO.File.ReadAllBytes(
System.IO.Path.GetFullPath(Server.MapPath("~/App_Data/Images/no_image.jpg"))),
"image/jpeg");
// Resetting httppostedfilewrapper here doesn't work
studentViewModel.HttpPostedFileBase= studentViewModel.StudentImageFileBase;
return View(studentViewModel);
}
}