Ajax file upload in .Net 6 Razor pages sends Null in the codebehind


Already tried This Answer but it did not work. So seeking help.

I have a .Net 6 Razor page from where I am trying to upload a file.

Here is my AjaxFileUpload.CSHtml

<h3>Ajax File Upload</h3>

 <form method="post">
    <div class="mb-3">
      <label for="formFile" class="form-label">Select File 1</label>
      <input class="form-control" type="file" id="formFile1">
      <button type="button" class="btn btn-info" onclick="UploadFile1ViaAjax()">Upload File 1</button>
      <span id="File1UploadStatus"></span>

The Ajax Call

function UploadFile1ViaAjax()
   var file1 = $('#formFile1').prop("files")[0];
   var url = "/Employees/AjaxFileUpload?handler=UploadFile1";
   formData = new FormData();
   formData.append(file1.name, file1);

   alert("Uploading file 1 : " + file1.name);

        type: "POST",
        url: url,
        contentType: 'multipart/form-data',
        contentType: false,
        processData: false,            
        data: formData, 
        headers: {
        success: function (result) {
            alert("success: " + JSON.stringify(result));
        failure: function (result) {
        error: function (result) {
        }).done(function (result) {
                alert("ajax call complete.");


Finally here is the code behind method AjaxFileUpload.CSHtml.cs

    public IActionResult OnPostUploadFile1(IFormFile formData)
        if (formData != null)
            return new ObjectResult(new { status = "success" });
        return new ObjectResult(new { status = "fail" });

When I upload a file and click the button, The ajax call works and debugger is hit in the code behind method, but the problem is, the IFormFile object is always coming as null.

Why is this happening? How can I get the IFormFile object populated with file data that I am uploading ?

>Solution :

The problem is because the name of the parameter inside your C# endpoint doesn’t match the ajax call. Try setting the formdata.append("fileName", file) and call the parameter in your endpoint fileName too. Other wise you should upload it either through submitting a form. Or uploading the file as base64

Leave a ReplyCancel reply