我有一些数据和文件应该在同一个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; }
}
答案 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));
}