7

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?

tereško
  • 56,151
  • 24
  • 92
  • 147
kevskree
  • 3,532
  • 3
  • 22
  • 32

1 Answers1

10

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:

tpeczek
  • 22,947
  • 3
  • 69
  • 75
  • Thank you for your response. That was my suspicion but I just wanted to make sure. The articles you provided were helpful. Thank you again. – kevskree Sep 14 '12 at 21:10