When I attempt to upload images to my MVC controller action and there is a validation error, I have to click through each of the buttons and find all of my files again.
If I have a view that consists of
<input type="file" id="file0" name="Files[0]" />
<input type="file" id="file1" name="Files[1]" />
and a controller action like
public ActionResult Create(ModelClass model, IEnumerable<HttpPostedFileBase> Files)
{
if(ModelState.IsValid)
{
//do work
if(PhotoValidation.IsValid(Files))
{
//do work
}
else
{
ModelState.AddModelError("","Photos not valid");
}
}
return view(model); // Way to return photos back to the view on modelstate error?
}
The files get posted to the server fine but if there is a model validation error, is there any way to return the model AND the Files so the user doesn't have to upload them again?
This is not possible. The value of a intput type="file" is never used on parsing an HTML page. That's a huge security risk, so no modern browser will allow them to 'retain' values.
If you are sure that your clients are using browser with HTML5 support, you can try using JavaScript File API in order to eliminate postbacks - check following articles:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With