在同一个AJAX请求中发布文件和对象

时间:2015-09-30 10:02:28

标签: javascript jquery asp.net ajax http-post

我有一些数据和文件应该在同一个AJAX请求中发布。尝试了一些解决方案,但我总是在控制器中获得null(文件发送正常,当我将Tester类更改为简单string时,它也有效。)

我的JS:

function sendAjaxWithFile (formData, successCallback, errorCallback) {
    successCallback = successCallback || function () { };
    errorCallback = errorCallback || function () { };

    $.ajax({
        url: "/Test/Save",
        type: "POST",
        data: formData,
        cache: false,
        processData: false,
        contentType: false,
        success: successCallback,
        error: errorCallback
    });
}

var data = new FormData();
data.append("tester", { Name: "QWERTY" });
data.append("someFile", file);

$scope.sendAjaxWithFile(data, function (response, textStatus, jqXHR) {
}, function (jqXHR, textStatus, errorThrown) {
});

服务器端代码:

[AjaxOnly]
[HttpPost]
[Route("Save")]
public async Task<JsonResult> Save(Tester tester, HttpPostedFileBase someFile)
{
    return await Task.FromResult(Json(0));
}

Tester上课:

public class Tester
{
    public string Name { get; set; }
    public DateTime Date { get; set; }
}

1 个答案:

答案 0 :(得分:0)

我做了一个解决方法,因为我觉得它不能以正常的方式解决......

我的解决方案是发送从我的JS对象序列化的字符串数据。

data.append("serializedJsonString", JSON.stringify({ Name: "QWERTY" })); // I can serialize what I want to

我需要更改Save方法的参数以获取JSON字符串数据并手动将其转换为Tester类:

[AjaxOnly]
[HttpPost]
[Route("Save")]
public async Task<JsonResult> Save(string serializedJsonString, HttpPostedFileBase someFile)
{
    var decodedJson = HttpUtility.UrlDecode(serializedJsonString);
    var jTester = JObject.Parse(decodedJson);
    var tester = new Tester { Name = jTester["Name"].ToString() };

    return await Task.FromResult(Json(0));
}