0

I have an AJAX call which passes data along with a file to the ViewModel and calls the controller:

function fncInsTrainingLog()
{
    var trainingtitle = getValOf("trainingTitle");
    var ImageFile = $('#imageUploadForm')[0].files[0];

    var sdata = {
        TrainingTitle :trainingtitle,
        ImageFile : ImageFile
    }

    $.ajax({
        url: "/Capability/InsTrainingLog",
        type: "POST",
        data: JSON.stringify(sdata),
        contentType: "application/json",
        dataType: "json",
        success: function () {
            location.reload();
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert("A problem has been encountered. Please contact the web administrator.");
        }
    });
} 

Here is my controller:

[HttpPost]
public JsonResult InsTrainingLog(TrainingModel trainingModel)
{

    // Psuedo code to save file to drive
    // get file from TrainingModel 
    // save(file)

    string sp = "usp_InsTrainingLog";

    object[] param =
    {
        "@TrainingTitle", trainingModel.TrainingTitle
    };

    dbHelper.ExecuteProcedureNonQuery(sp, param);
    var result = param;

    return Json(result, JsonRequestBehavior.AllowGet);
}

ViewModel:

   public sealed class TrainingModel
    {
        public HttpPostedFileBase ImageFile { get; set; }
        public string TrainingTitle { get; set; }

    }

The ImageFile in the TrainingModel returns a null but the TrainingTitle is fine. Why can't the ViewModel read the file from the AJAX call?

How do I pass the file to the ViewModel and save the image to my PC?

Odie
  • 343
  • 3
  • 14
  • Possible duplicate of [How to use FormData for ajax file upload](https://stackoverflow.com/questions/21044798/how-to-use-formdata-for-ajax-file-upload) – devlin carnate Jun 18 '19 at 21:06
  • In this line: var trainingtitle = getValOf("trainingTitle"); What kind of element is trainingTitle? Html tag? id? class? other? – BattlFrog Jun 18 '19 at 22:30

2 Answers2

1

You need use AJAX call with FormData(), change contentType to contentType: false, and add processData: false.

I reproduced and it worked

var trainingtitle = $("#trainingTitle").val();
                var ImageFile = $('#imageUploadForm')[0].files[0];

                var formData = new FormData();
                formData.append('TrainingTitle', trainingtitle);
                formData.append('ImageFile', ImageFile);


                $.ajax({
                    url: "/Product/InsTrainingLog",
                    type: "POST",
                    data: formData,
                    contentType: false,
                    processData: false,
                    dataType: "json",
                    success: function () {
                        location.reload();
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        alert("A problem has been encountered. Please contact the web administrator.");
                    }
                });



Updated cshtml


    <div id="uploadForm">
                    <input type="text" name="TrainingTitle" id="trainingTitle" />
                    <input type="file" name="ImageFile" id="imageUploadForm" />
                    <button type="button" onclick="fncInsTrainingLog()">Submit</button>
                </div>

    function fncInsTrainingLog() {
                var trainingtitle = $("#trainingTitle").val();
                var ImageFile = $('#imageUploadForm')[0].files[0];

                var formData = new FormData();
                formData.append('TrainingTitle', trainingtitle);
                formData.append('ImageFile', ImageFile);
                //var sdata = {
                //    TrainingTitle: trainingtitle,
                //    ImageFile: ImageFile
                //}

                $.ajax({
                    url: "/Product/InsTrainingLog",
                    type: "POST",
                    data: formData,
                    contentType: false,
                    processData: false,
                    dataType: "json",
                    success: function () {
                        location.reload();
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        alert("A problem has been encountered. Please contact the web administrator.");
                    }
                });
            }
Hien Nguyen
  • 21,001
  • 7
  • 35
  • 48
0

I would use $.ajaxForm()...

@using (Html.BeginForm())
{
    <div id="status"></div>

    <input type="text" name="TrainingTitle" />
    <input type="file" name="ImageFile" accept="image/*" />
    <input type="submit" value="Upload File to Server" />
}


<script>
    (function () {
       var status = $('#status');
        $('form').ajaxForm({
            complete: function (xhr) {
                    status.html(xhr.responseText);
                }
            }
        });
    })();
</script>

Code not tested!

Frank Navarrete
  • 101
  • 2
  • 10