我的目标是:
我正在尝试将值发送到控制器的方法中以更新数据库(该数据库通过API远程连接)。
我已经检查了几个教程(例如How to pass parameters in $ajax POST?),但是我无法在控制器中发送数据,由于ajax调用,我出现了500错误。
你能告诉我该怎么做吗?
查看
$(document).ready(function () {
$.ajax({
url: "http://localhost:44338/Registration/ShowRegistration",
type: 'POST',
data: JSON.stringify({ "id": 1 }),
contentType: 'application/JSON',
success: function (data) { },
error: function () { }
})
});
控制器
[Authorize]
[HttpPost]
public async Task<ActionResult> ShowRegistration(Models.RegisterForm rF)
{
try
{
var test = rF.id;
Ok("success");
}
catch (Exception e)
{
Console.Write(e.Message);
return BadRequest();
}
return View();
}
模型
public class RegisterForm
{
public string id { get; set; }
}
答案 0 :(得分:0)
现在先创建模型(标准方式)
尝试一下,让我知道。
public class InfoModel
{
public string id { get; set; }
//Add your model fields here
}
您的Api
[HttpPost]
public async Task<ActionResult> ShowRegistration(InfoModel im)
{
//code
}
您的ajax调用对此进行测试,然后发送更多数据:
$.ajax({
url: "url",
type: 'POST',
data: JSON.stringify({"id": id}),
contentType: 'application/JSON',
success: function (data) { },
error: function () {};
})
测试示例:-
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
$.ajax({
url: "http://localhost:62211/Home/ShowRegistration",
type: 'POST',
data: JSON.stringify({ "id": 1 }),
contentType: 'application/JSON',
success: function (data) { },
error: function () { }
})
});
</script>
</head>
<body>
</body>
</html>
Api
using System.Threading.Tasks;
using System.Web.Mvc;
namespace WebApplication5.Controllers
{
public class HomeController : Controller
{
[HttpPost]
public async Task<ActionResult> ShowRegistration(Models.info inf)
{
// Access inf.id
return null;
}
}
}