0

I'm currently working on Web API and MVC in the same ASP.NET Core project. I'm trying to upload a file. But I'm stuck at the front end because the data is just null or Illegal invocation

HTML

<form class="needs-validation" enctype="multipart/form-data"  novalidate>
    <input class="file-upload" type="file" name="file" size="40" accept=".png, .jpg, .jpeg, .gif">
    <button class="btn btn-primary Save-Exit" type="button" onclick="return SaveExit()">Save and Exit</button>
</form>

JS

Here I commented out processData: false because it will return null to all my data at formVM when pass it to client controller

function SaveExit() {
    var GetImages = $('[name="file"]');
    console.log(GetImages[0].files)
    var data = {
        Total: $("#Total").val(),
        Attachments : GetImages[0].files
    };

    $.ajax({
        url: "/Forms/InsertForm",
        type: "Post",
        'data': data,
        'dataType': 'json',
        //processData: false,
        success: function (result) {
            window.location.href = "/Reimbusments/Expense"
        },
        error: function (error) {
            console.log(error)
        }
    })
    return false;
}

Client controller:

[HttpPost]
public JsonResult InsertForm(FormVM formVM)
{
    var sessionExpense = HttpContext.Session.GetString("ExpenseID");
    var result = formRepository.InsertForm(formVM, sessionExpense);
    return Json(result);
}

Client repo:

public HttpStatusCode InsertForm(FormVM entity, string expensed)
{
    entity.ExpenseId = Int32.Parse(expenseid);
    StringContent content = new StringContent(JsonConvert.SerializeObject(entity), Encoding.UTF8, "application/json");
    var result = httpClient.PostAsync(address.link + request + "FormInsert", content).Result;
    return result.StatusCode;
}

View model class:

public class FormVM
{
    public int FormId { get; set; }
    public float? Total { get; set; }
    public int ExpenseId { get; set; }
    public IFormFile Attachments { get; set; }
}

I can call my API controller but because the formVM is null the API does not work

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

1 Answers1

1

You can try to use the following code:

js:

function SaveExit() {
            var formData = new FormData();
            formData.append("Total", $("#Total").val());
            formData.append("Attachments", $('[name="file"]')[0].files[0]);

            $.ajax({
                url: "/Forms/InsertForm",
                type: "Post",
                data: formData,
                processData: false,
                contentType: false,
                success: function (result) {
                    window.location.href = "/Reimbusments/Expense"
                },
                error: function (error) {
                    console.log(error)
                }
            })
            return false;
        }

result: enter image description here

Yiyi You
  • 16,875
  • 1
  • 10
  • 22
  • Thank you very much, it works like charm. Can you explain to me what happens with the code? – Bagoes Heikhal Dec 30 '21 at 04:16
  • `$('[name="file"]')[0].files` is a list,so you need to use `$('[name="file"]')[0].files[0]` to get a file,and we usually use `FormData` to pass files to action.`processData: false` will not serialize data when using it,`contentType` option to `false` is used for multipart/form-data forms that pass files.For `proccessData` and `contentType`,you can also refer to the [link](https://stackoverflow.com/questions/20795449/jquery-ajax-form-submission-enctype-multipart-form-data-why-does-contentt). – Yiyi You Dec 30 '21 at 05:56