Master
Master

Reputation: 2163

Parameters are coming in as null for Ajax Post method to Controller

I have this bit of code that triggers on click. When I set a breakpoint at SaveNewProduct all the values are null. I tried to create a input object, I tried to add in each property manually, nothing worked. May I get any tips or suggestion.

var input = {
    name: name,
    type: type,
    description: description,
    category: category,
    file: file.files[0],
    acronym: acronym
};

$.ajax({
    type: "POST",
    url: '/Admin/SaveNewProduct',

    processData: false,
    data: {
        name: name,
        type: type,
        description: description,
        category: category,
        file: file.files[0],
        acronym: acronym,
        input: input
    },
    success: function (response) {
        alert("saved okay");
    }
});

[HttpPost]
public async Task<ActionResult> SaveNewProduct(SaveNewProductInput input)
{
    ...
    //breakpoint here, input values are all null
    ...
}

SaveNewProductInput.cs

public class SaveNewProductInput
{
    public string Name { get; set; }
    public string Acronym { get; set; }
    public string Type { get; set; }
    public string Category { get; set; }
    public string Description { get; set; }
    public HttpPostedFileBase File { get; set; }
}

I also tried remove processData, i Am presented with this error Uncaught TypeError: Illegal invocation

Upvotes: 1

Views: 1158

Answers (3)

Alexander
Alexander

Reputation: 9642

You need to use FormData to send files in request with processData and contentType set to false

var formData = new FormData();
formData.append("name", name);
formData.append("type", type);
formData.append("description", description);
formData.append("category", category);
formData.append("file", file.files[0]);
formData.append("acronym", acronym);

$.ajax({
    url: "/Admin/SaveNewProduct",
    type: "POST",
    data: formData,        
    processData: false,
    contentType: false,
    success: function (response) {
        alert("saved okay");
    }
});

Upvotes: 1

TejasGondalia
TejasGondalia

Reputation: 168

var input = {},
input.Name = name;
input.Type = type;
input.Description = description;
input.Category = category;
input.File = file.files[0];
input.Acronym = acronym;
$.ajax({
    url: "/Admin/SaveNewProduct",
    type: "POST",
    data: JSON.stringify(input),
    dataType: "json",
    contentType: 'application/json; charset=utf-8',
    success: function (response) {
    }
});

[HttpPost]
public async Task<ActionResult> SaveNewProduct(SaveNewProductInput input)
{
    ...
}

Upvotes: 0

Nils
Nils

Reputation: 1020

JQuery automatically converts the 'data' object into request parameters, but I think it not doing that because you set 'processData' to false. Please remove processData and try.

Upvotes: 0

Related Questions