Request.File.Count is still set to 1 when uploading files to ASP.Net MVC detected a previous error

I am developing a form in ASP.Net MVC where it contains <input type="file" />, which is optional on the 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 the user uploads a file that has no content, the form will throw an exception and ask the user about it - which is expected.

Now, if the user decided that they will no longer upload any file, and click the submit button, the previous exception will still be displayed, which is quite difficult.

Request.Files , - 1... , , , <input type="file" />.

- ? , , ?

!

+3
2

. , , - . , , .

!

-1

, , :

 if(Request.Files.Count >  0)
 {
     if(Request.Files[0].ContentLength > 0)
     {
         //Upload the file... 
     }
 }
+5

Source: https://habr.com/ru/post/1714367/


All Articles