Home > Enterprise >  Iformfile Illegal invocation & Null Value
Iformfile Illegal invocation & Null Value

Time:12-30

I'm currently working on web API and MVC in the same project asp.net core. 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  enctype="multipart/form-data"  novalidate>
  <input  type="file" name="file" size="40" accept=".png, .jpg, .jpeg, .gif">
  <button  type="button" onclick="return SaveExit()">Save and Exit</button>
</form>

JS

here I comment 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;
}

VM

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

CodePudding user response:

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

  • Related