Search code examples
c#asp.net.netasp.net-mvcrazor

Request.Files.Count is always 0 MVC .net


Ok so Im trying to do file uploads on my webpage however I have run into the issue where Request.Files.Count > 0 is always 0 and wont enter the if statement. I have tried multiple ways of doing this and looked at multiple answers amongst this similar issue(there were a lot) but none of the solutions worked.

Controller

public class TicketController : CommonController
{
        [HttpPost]
        public async Task<ActionResult> Create(TicketViewModel model)
        {
            
            if (ValidateModel(model))
            {

                if (Request.Files.Count > 0) /*This is always 0*/
                {
                   HttpPostedFileBase file = Request.Files[0];
                }
            }
         }
}

View

@using (Html.BeginForm("Create", "TicketController", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <div class="editor-field">
        @Html.TextBoxFor(model => model.FileUpload, new { type="file", name = "FileUpload"})
        @Html.ValidationMessageFor(model => model.FileUpload) 
    </div>

}

Model

public class TicketViewModel
{
     public HttpPostedFileBase FileUpload { get; set; }
}

Tried adding or removing and changing the name in the View and the variable in the Model. But no luck always hits zero even when filled. My understanding is if a request key is detected it updates the variable to actually contain something. So there is a disconnect from my View and Controller and I can't figure it out. Any direction would be greatly appreciated.

EDIT: Submit Button

<div class="form-group bottom-button-row">
    <div class="col-md-offset-2 col-lg-offset-2 col-sm-offset-4">
        <div class="col-sm-12 btn-panel">
            <div class="float-left">
                <input type="button" value="Submit" class="btn btn-primary" data-bind="click:submit,disable:submitting" />
                <a role="button" class="btn btn-default" href="@ViewBag.CancelUrl" data-bind="attr:{disabled:submitting}">Cancel</a>
            </div>
            <div class="loader" data-bind="visible: submitting" style="display: none;"></div>
        </div>
    </div>
</div>

Solution

  • Turns out another CSHTML file was calling this CSHTML file within a form already so I was nesting a form within a form which isn't supported I updated the outer form and all is well and it works. Comment your code people!