JasCav JasCav - 1 year ago 144
Javascript Question

Ajax form submission with files in ASP.NET MVC 6

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">

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
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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download