使用 http post 方法向 asp.net mvc core 3 操作发送具有多个参数的 ajax 请求时存在问题。参数不绑定。在 dot net 框架 asp.net web api 中存在类似的限制,但在 asp.net mvc 操作中没有。
我想知道 ASP.NET Core 3 MVC 中是否有解决此问题的方法,或者这是新的限制?
行动:
public string SomeAction([FromBody]string param1, [FromBody]IEnumerable<SomeType> param2, [FromBody]IEnumerable<SomeType> param3)
{
//param1 and param2 and param3 are null
}
client:
$.ajax({
contentType: 'application/json',
data: JSON.stringify({
"param1": "someString",
"param2": someList,
"param3": someList
}),
type: "POST",
dataType: "json",
url: "/SomeController/SomeAction",
success: function (result) {
},
error: function (error) {
console.error(error);
}
}
);
在新版本中,操作需要明确说明他们期望从何处绑定模型。
创建一个模式来保存所有必需的数据
public class SomeActionModel {
public string param1 { get; set; }
public IEnumerable<SomeType> param2 { get; set; }
public IEnumerable<SomeType> param3 { get; set; }
}
更新操作以期望请求正文中的数据
public IActionResult SomeAction([FromBody] SomeActionModel model) {
if(ModelState.IsValid) {
string param1 = model.param1;
IEnumerable<SomeType> param2 = model.param2;
IEnumerable<SomeType> param3 = model.param3;
//...
return Ok();
}
return BadRequest(ModelState);
}
客户端还应该以正确的格式发送数据
var model = {
param1: GeometricNetworkTrace_Class.flags,
param2: GeometricNetworkTrace_Class.barriers,
param3: feederIds
};
$.ajax({
contentType: 'application/json',
data: JSON.stringify(model),
type: "POST",
dataType: "json",
url: "/controllerName/actionName",
success: function (result) {
},
error: function (error) {
console.error(error);
}
});
参考ASP.NET Core 中的模型绑定 https://learn.microsoft.com/en-us/aspnet/core/mvc/models/model-binding
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)