views:

286

answers:

1

Hi there,

I'm developing a form in ASP.Net MVC where it contains an <input type="file" /> which is not mandatory in a form.

In my controller, I have this code:

[AcceptVerbs(HttpVerbs.Post)]
[ValidateInput(false)]
public ActionResult Create(FormCollection collection) {
        ...

        //get uploaded file
        if (Request.Files.Count > 0)
        {
            file = Request.Files["imgFileUpload"];
            if (file.ContentLength == 0)
            {
             throw new InvalidOperationException("File contents are empty");
            }
            ...
        } 
        ...
}

Now, when a user uploads a file that has no content, the form would raise an exception and prompt the user about it -- which is expected.

Now, if a user decided that they are not going to upload any file anymore and click the submit button, the previous exception would still show, which is quite bizzare.

I've tried checking the values for Request.Files and noticed that its count is still set to 1... it still thinks that there is a file there, given that the user has not placed any file on the <input type="file" /> control.

Has anybody encountered this? If so, what steps did you do to prevent from re-executing the previous exception again?

Thank you so much!

A: 

Hi Guys,

Just managed to find a way to solve this. What I did was I need to check if the input file controller has any values on it. If it does, then upload the file, otherwise leave it as it is.

HTH!

mallows98