views:

306

answers:

2

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?

+1  A: 

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.

Darin Dimitrov
A: 

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.

enorl76