如何将模型绑定器与Ajax Post一起使用在.net核心mvc中



我是.net核心MVC的新手,正在尝试执行类似于.net框架MVC的Ajax帖子。我只是想将一个int值POST到下面的控制器操作中。Ajax调用命中控制器,但操作参数始终为0。我验证了Ajax请求负载中发送的整数值是否正确。我错过了什么?

public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult Ajax_GenerateSecretNum([FromBody]int lower)
{
return Json(new { success = true });
}
$.ajax({
url: '@Url.Action("Ajax_GenerateSecretNum", "Home")',
type: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: { lower: lower },
success: function (response) {
}
});

您可以为控制器参数创建一个模型(DTO),并在发布到控制器之前对数据使用JSON.stringify()

$.ajax({
url: '@Url.Action("Ajax_GenerateSecretNum", "Home")',
type: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: JSON.stringify({ lower: lower }),
success: function (response) {
}
});
public class ModelDto
{
public int Lower { get; set; }
}
[HttpPost]
public IActionResult Ajax_GenerateSecretNum([FromBody]ModelDto model)
{
// model.Lower should contain your int
return Json(new { success = true });
}
$.ajax({
url: '@Url.Action("Ajax_GenerateSecretNum", "Home")',
type: 'POST',               
data: { "lower": lower, "upper": upper },
success: function (response) {
}   
});

将我的jQueryajax更改为上面的示例解决了这个问题。我不知道为什么,但指定额外的ajax参数似乎会导致值绑定失败。在更改ajax之后,我还能够从控制器操作中删除[FromBody]属性。

您可以执行以下操作:

$.ajax({
method: "POST",
data: { "Property1": "value1", "Property2": "value2"},
url: "@Url.Action("Ajax_GenerateSecretNum", "Home")",
success: function (data) {
//success login
},
error: function (data) {
alert('error' + data.status);
}
});

控制器如下所示:

[HttpPost]
public ActionResult Ajax_GenerateSecretNum(ModelClass modelClass)
{
//You logic will be here
}

最新更新