$.ajax({ url: '/MyController/MyAction', type: 'POST', data: { username: 'test', password: 'test' }, dataType: 'json', contentType: 'application/x-www-form-urlencoded; charset=UTF-8', success: function (data, textStatus, xhr) { console.log(data); }, error: function (xhr, textStatus, errorThrown) { console.log('Error: ' + errorThrown); } });
public class MyModel { public string Username { get; set; } public string Password { get; set; } }
[HttpPost] public IActionResult MyAction(MyModel model) { if (model != null && ModelState.IsValid) { // 执行相应操作 return Json(new { success = true }); } else { return Json(new { success = false }); } }
如果数据被正确的序列化并且contentType被设置为'application/json; charset=utf-8',在使用以下方法时,确保参数名要与json数据对象的属性名相匹配:
[HttpPost] public IActionResult MyAction(string username, string password) { if (!string.IsNullOrWhiteSpace(username) && !string.IsNullOrWhiteSpace(password)) { // 执行相应操作 return Json(new { success = true }); } else { return Json(new { success = false }); } }