littlechris
littlechris

Reputation: 4184

ASP.NET MVC Request.Files not surviving Model.IsValid = false

I have a POST controller action like:

    if (ModelState.IsValid)
    {
        try
        {
            //.. save and redirect code here
        }
        catch
        {
            //.. add errors to model state
        }
    }

    return View(myModel);

My request.files can contain 2 images from tags like:

<input id="MyImage" name="MyImage" type="file" />

This works fine when the model is valid, the save completes and I then re-direct.

However my problem comes when the model isn't valid and I return my object to the view. The request no longer has the files in Request.Files. is there a way to pass them down to the view to be stored in the input tag?

Upvotes: 0

Views: 860

Answers (2)

enorl76
enorl76

Reputation: 2655

Try saving the file first to a temp area, then calling Model.IsValid. Gets a little more complicated, but it's necessary given your desire to upload a file (probably with a validated record) Mark somewhere that you've already uploaded a file, in a hiddenfield or something, and use that when Model.Isvalid returns true so you can package up your file along with your new and valid record.

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1039328

For security reasons you cannot set the value of an input type="file" tag. Imagine visiting a malicious site which could set the value and post a form with javascript stealing any file on your computer.

Upvotes: 1

Related Questions