Returning HttpPostedFileBase to view on validation error
Asked Answered
L

1

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?

Lettering answered 13/9, 2012 at 21:13 Comment(0)
C
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:

Cat answered 14/9, 2012 at 7:9 Comment(1)
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.Lettering

© 2022 - 2024 — McMap. All rights reserved.