2

I am using the jquery-ajax-unobtrusive library to add in the previously existing tag helpers for quickly creating a form that submits via an ajax request.

This gives me something like this:

<form id="person-create" enctype="multipart/form-data" asp-controller="Person" asp-action="Create" asp-route-id="1" data-ajax="true" data-ajax-method="POST" role="form">
    <!-- There are other inputs for the other items. -->
    <input id="photo-upload" asp-for="Photo" type="file">
</form>

The form submits great, except for the fact that a file input that I have within the form always comes through with a null value. As a test, I turned the form back to not use ajax and everything submits properly. I also tried to manually perform the submission by calling jQuery's .ajax function directly, but, that also experienced the same issue as using jquery-ajax-unobtrusive.

My controller endpoint looks like this:

public async Task<IActionResult> Create(int id, PersonViewModel person)
{
  // Do stuff...
}

And in PersonViewModel, I have a class that looks something like this:

public class PersonViewModel
{
  public int PersonId { get; set; }
  public string Name { get; set; }
  public IFormFile Photo { get; set; }
}

Am I just missing something obvious, or is there something inherently different when submitting a file via an Ajax form submission?

JasCav
  • 34,458
  • 20
  • 113
  • 170
  • Try giving the same Id and Name as your modelproperty to the HTML page and then check – Shashank Sood Jun 24 '16 at 18:42
  • You cant submit files using `jquery.unobtrusive-ajax`. You can use the jQuery `.ajax()` methods along with `FormData` as explained in [this answer](http://stackoverflow.com/questions/29293637/how-to-append-whole-set-of-model-to-formdata-and-obtain-it-in-mvc/29293681#29293681) –  Jun 24 '16 at 23:43

1 Answers1

1

Per Stephen's comment, jquery.unobtrusive-ajax cannot be used to submit files. Instead, the jQuery .ajax() method and FormData should be used to achieve this.

For more information, see Stephen's answer on another question.

Community
  • 1
  • 1
JasCav
  • 34,458
  • 20
  • 113
  • 170