在使用 jQuery 的 AJAX 方法将 JSON 数据发送到 C# MVC 控制器时,如果传入的数据为空,可能是由于以下几个原因造成的:
{}
中。Content-Type
头为 application/json
,以便服务器能够正确解析 JSON 数据。[FromBody]
属性标记的模型类。下面是一个简单的示例,展示如何使用 jQuery AJAX 发送 JSON 数据到 C# MVC 控制器:
JavaScript (jQuery AJAX):
$.ajax({
url: '/YourController/YourAction',
type: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: JSON.stringify({ key: 'value' }), // 确保这里的 JSON 数据格式正确
success: function (response) {
console.log('Success:', response);
},
error: function (xhr, status, error) {
console.error('Error:', error);
}
});
C# MVC 控制器:
public class YourController : Controller
{
[HttpPost]
public ActionResult YourAction([FromBody] YourModel model)
{
if (model == null)
{
return Json(new { success = false, message = "Data is empty" });
}
// 处理接收到的数据...
return Json(new { success = true, message = "Data received" });
}
}
public class YourModel
{
public string Key { get; set; }
}
解决步骤:
data
字段中的 JSON 字符串格式正确。contentType
是否设置为 application/json
。[FromBody]
属性,并且参数类型与发送的 JSON 数据结构匹配。如果问题仍然存在,可以进一步检查网络请求的详细信息,或者在服务器端添加日志记录,以便更好地理解数据在哪个环节丢失或被修改。
参考链接:
领取专属 10元无门槛券
手把手带您无忧上云