0

I have an action in my ASP.NET Core MVC controller:

[HttpPost]
public async Task<IActionResult> ImportDeviceAsAdmin(UserUploadDeviceVM userUploadDeviceVM)
{
    var uploadResult = await this.userService.UploadFilesAsync(userUploadDeviceVM.UserId, userUploadDeviceVM.Files);

    return uploadResult ? (IActionResult) Ok("success") : BadRequest("error");
}

and I have a piece of jQuery code:

$(document).ready(function () {
    $("input[type='submit']").click(function () {
        importUserFiles();
    });
});

function importUserFiles() {
    const formData = new FormData();
    const userId = $("#user-emails-dropdown option:selected").val();

    formData.append("UserId", userId);

    const fileInput = $("#file-input")[0];
    for (let i = 0; i < fileInput.files.length; i++) {
        formData.append("Files", fileInput.files[i]);
    }

    importFileAjax(formData,
        function(response) { console.log(response); },
        function(response) { console.log(response); });
}

function importFileAjax(formData, successCallback, errorCallback) {
    $.ajax({
        url: "/Admin/ImportDeviceAsAdmin",
        data: formData,
        processData: false,
        contentType: false,
        type: "POST",
        success: successCallback,
        error: errorCallback
    });
}

After I click a Submit button, my model goes to the specified action and the action works with it absolutely perfectly, no problem with it. But my jQuery AJAX call somehow hits neither success nor error statements. How can I fix it without specifying async: false? I have been trying all kinds of promises, async/await etc. from all the Internet but still couldn't fixed the error.

Part of my view with the Submit button:

<div id="file-uploader-container">
        <form method="post" enctype="multipart/form-data">
            <div class="dropdown-wrapper">
                <label for="user-emails-dropdown">Select user</label>
                <div>
                    <select id="user-emails-dropdown" asp-items="ViewBag.Emails" asp-for="UserId">
                        <!-- there are user emails displayed-->
                    </select>
                </div>
            </div>
            <div class="file-upload-button-container">
                <input id="file-input" name="Files" type="file" multiple />
            </div>
            <div class="file-upload-button-container">
                <input class="btn btn-primary" type="submit" value="Upload" />
            </div>
        </form>
    </div>
el_nektarin
  • 343
  • 1
  • 14
  • I don't see where you are canceling the `
    ` submit before doing the ajax call
    – Taplar Jan 08 '20 at 17:10
  • @Taplar I don't understand you... In my form I didn't mentioned `asp-action` and `asp-controller` attributes, so without the JS the form cannot be submitted properly at all. Please correct me in the case I wrong. – el_nektarin Jan 08 '20 at 17:14
  • If you click a submit button in a form, it will submit. If no action or method is provided it will default to GET (i believe) and will submit to the same url as the page it is on – Taplar Jan 08 '20 at 17:15
  • Ok, I'll check it, but don't the `form method="post"` does the trick? – el_nektarin Jan 08 '20 at 17:16
  • So it will POST to the same url the form is on. The point being, if you are not wanting to use a form in the traditional sense, you should consider changing your button from a submit to just a normal button, and prevent default on the form submit in case a user hits enter on one of the text or other inputs to generate a submit event. Otherwise the form will submit and make the page transfer, killing the logic you are trying to do with the ajax – Taplar Jan 08 '20 at 17:16
  • @Taplar did as you said, nothing changed at all: goes to action as expected, but doesn't hit `success` and `error` – el_nektarin Jan 08 '20 at 17:23
  • What specifically did you change? – Taplar Jan 08 '20 at 17:24
  • @Taplar I changed `submit` button to normal button with ID, and the target button of jQuery `click` event respectively – el_nektarin Jan 08 '20 at 17:26
  • "normal button"? `` ? – Taplar Jan 08 '20 at 17:26
  • @Taplar yes, as you said, from `` to `` – el_nektarin Jan 08 '20 at 17:27
  • No, that's not the same. `` === ` – Taplar Jan 08 '20 at 17:28
  • @Taplar wow, it worked! But why `` does the job while ` – el_nektarin Jan 08 '20 at 17:33
  • Of all three of those options, only type="button" does not generate a form submit. You can put that on an input or a button, and the form submit would not happen. Orginally `` was the way to make a submit button for a form. ` – Taplar Jan 08 '20 at 17:34
  • @Taplar yeas, thanks, already found an answer in the https://stackoverflow.com/questions/469059/button-vs-input-type-button-which-to-use, you can post your comment as the answer so I can +1 you if you want) – el_nektarin Jan 08 '20 at 17:36

0 Answers0