要解决此问题,我们可以使用JSON.stringify()将数据转换为JSON格式,并在Ajax请求中设置content-type为application/json。
以下是代码示例:
JavaScript代码:
var data = {
key1: "value1",
key2: null,
key3: "value3"
};
$.ajax({
type: "POST",
url: "/Controller/Action",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(data),
dataType: "json",
success: function(result) {
// handle success
},
error: function(xhr, textStatus, errorThrown) {
// handle error
}
});
控制器代码:
[HttpPost]
public ActionResult Action(MyModel model) {
// handle request
return View();
}
public class MyModel {
public string Key1 { get; set; }
public string Key2 { get; set; }
public string Key3 { get; set; }
}
在此示例中,我们将数据对象传递给Ajax请求,并将其转换为JSON格式。在控制器中,我们传递了一个MyModel类,其中包含与JavaScript对象相同的属性。即使对象中包含空值,我们在控制器中仍然可以正确接收数据。