kibowki
kibowki

Reputation: 4376

HTTP POST data not going from AJAX to C# MVC 5 Backend

As the title states, I'm trying to send data from a Javascript frontend to my C# MVC 5 backend, and it doesn't seem to make it. I've run through it with the debugger in Visual Studio and the data I'm trying to pass always ends up null.

Here is my front end code:

var file = $("#my-file").files[0];
file = file[0];
var formData = new FormData();
var MyData = {
    Name: "Form 133",
    Attachments: {
        Type: "Check"
    }
};
formData.append('file', file);
$.ajax({
    type: "POST",
    url: '/NMISProduct/Index',
    contentType: false,
    processData: false,
    data: { formData: formData, MyData: MyData },
    success: function (result) {
        console.log(result);
    },
    error: function (xhr, status, p3, p4) {
        var err = "Error " + " " + status + " " + p3 + " " + p4;
        if (xhr.responseText && xhr.responseText[0] == "{")
            err = JSON.parse(xhr.responseText).Message;
        console.log(err);
    }
});

Backend code:

[HttpPost]
public async Task<JsonResult> Index(MyData MyData)
{
    Debug.WriteLine(Request.Params["MyData"]);
    Debug.WriteLine(MyData.Name);
    try
    {
        foreach (string file in Request.Files)
        {
            var fileContent = Request.Files[file];
            if (fileContent != null && fileContent.ContentLength > 0)
            {
                // get a stream
                var stream = fileContent.InputStream;
                // and optionally write the file to disk
                var fileName = fileContent.FileName;
                var path = Path.Combine(Server.MapPath("~/App_Data/"), fileName);
                using (var fileStream = System.IO.File.Create(path))
                {
                    stream.CopyTo(fileStream);
                }
            }
        }
    }
    catch (Exception)
    {
        return Json("Upload failed");
    }
    return Json("File uploaded successfully");
}

public class MyData
{
    public string Name { get; set; }
    public Attachment Attachments { get; set; }
}

public class Attachment
{
    public string Type { get; set; }
}

As I stated, on the Backend MyData always ends up being null. What am I doing wrong?

Upvotes: 0

Views: 2585

Answers (2)

DavidDomain
DavidDomain

Reputation: 15293

jQuery docs state:

processData (default: true) Type: Boolean By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". If you want to send a DOMDocument, or other non-processed data, set this option to false.

The problem is that you are trying to send MyData as an object while setting processData to false. Which will result in the data not being processed before being send. The data property should contain a query string of the form key1=value1&key2=value2, or an object of the form {key1: 'value1', key2: 'value2'}, the latter will be converted into a query string before being send unless you are setting processData to false.

So if you want to send your formData along with the MyData you will need to append the MyData to the formData before sending it like so.

formData.append('Name', 'Form 133');
formData.append('Type', 'Check');

And then in the $ajax call add the FormData to the data property like so.

data: formData,

Upvotes: 1

DarkVision
DarkVision

Reputation: 1423

contentType setting to false you just told him to not sending any data in the header so basically the tag [HttpPost] become useless.

processData setting to false you told him not to process has and object so rendering MyData useless again by setting to true if i remember correctly it mean process anything beside string has a object.

$.ajax({
    url: "@Url.Action("Your METHOD", "Your Controller")",
    type: "POST",
    contentType: "application/json",
    data: JSON.stringify({ MyData: MyData}),
    success: function(response) {
        response ? alert("Process") : alert("Boom");
    }
});

Upvotes: 0

Related Questions