File Input does not upload file to MVC Action

For a project i’ve been trying to upload a file from my view to my controller action.
However, for some reason the action is reached but for the file i receive a null.

Here is my code:

Action:

[HttpPost]
[Route("UploadSickNote")]
public ActionResult UploadSickNote(HttpPostedFileBase file)
{
    // Do something with file

    return RedirectToAction("SickNotes");
}

View:

<form Controller="Documents" Action="UploadSickNote" method="post">
    <div>
        <input id="sicknote-upload" name="UploadedSickNote" asp-for="UploadedSickNote" type="file" accept="image/*" capture>
        <input id="sicknote-button-submit" type="submit"/>
    </div>
</form>

I have also tried using a viewmodel but with the same results.

Action:

[HttpPost]
[Route("UploadSickNote")]
public ActionResult UploadSickNote(SickNotesViewModel vm)
{
    // Do something with file

    return RedirectToAction("SickNotes");
}

ViewModel:

public class SickNotesViewModel
{
    public List<SickNoteElement> SickNoteElements { get; set; }
    public HttpPostedFileBase UploadedSickNote { get; set; }
}

I am using asp.net mvc 5 (not asp.net core) and a bit of vue.js for view functionalities.
Any ideas or tips are greatly appreciated.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Edit:

You have to make sure that your input name matches your controller so

<input id="sicknote-upload" name="file" asp-for="UploadedSickNote" type="file" accept="image/*" capture>

if with that doesnt work you could try also specifying the type of form you are sending

<form Controller="Documents" Action="UploadSickNote" method="post" enctype="multipart/form-data">

Method 2

Found the solution after some more searching.
I now receive the file in my viewmodel by changing my view to this:

   @using (Html.BeginForm("UploadSickNote", "Documents", FormMethod.Post, new { enctype = "multipart/form-data" }))
   {
            <div>
                <input id="sicknote-upload" name="UploadedSickNote" type="file" accept="image/*" capture>
                <input id="sicknote-button-submit" type="submit"/>
            </div>
   }


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x