0

I got a regular POST in my mvc app:

    @using (Html.BeginForm("Update", "AController", FormMethod.Post))
    {
        <div style="margin-bottom:20px"></div>
        @Html.AntiForgeryToken()
        <div class="form-input">
            <input class="form-control" type="text" name="@(nameof(Model.Name))" value="@(Model.Name)" />
        </div>
        <br />

        <div class="form-input">
            <input class="form-control" type="text" name="@(nameof(Model.Name2))" value="@(Model.Name2)" />
        </div>
        <br />

        <div>
            <input type="file" name="Image" id="Image" name="@(nameof(Model.Image))" value="@(Model.Image)" />
        </div>
        <button type="submit" class="btn btn-primary btn-sm">TEXT HERE</button>
    }

Now when doing the submit the two regular text fields gets binded the model but the file does not. After some reading it seems like the upload part should be in a separate form, is that correct?

I really want to avoid having two different POST as it does not fit the design of the page.

President Camacho
  • 1,860
  • 6
  • 27
  • 44

1 Answers1

1

You should be able to get the posted file from the Request directly in the controller with following code

if(Request.Files.Count > 0)
{
    var file = Request.Files[0];
    ...
}

But you need to add the multipart/form-data to your form

@using (Html.BeginForm("Update", "AController", FormMethod.Post, new { enctype="multipart/form-data" }))

Check What does enctype='multipart/form-data' mean? for reference on the multipart/form-data

Janne Matikainen
  • 5,061
  • 15
  • 21