问题描述
使用http post方法将具有多个参数的ajax请求发送到asp.net mvc core 3操作时出现问题.参数不绑定.在点网框架ASP.NET Web API中有类似的限制,但在ASP.NET MVC操作中没有.我想知道在asp.net core 3 mvc中是否有解决方法,还是这是新的限制?动作:
There is problem in sending ajax requests that have multiple parameters to asp.net mvc core 3 action using http post method. the parameters do not bind. In dot net framework asp.net web api there was similar limitation but not in asp.net mvc actions.I want to know is there work around this in asp.net core 3 mvc or is this the new limitation?action:
public string SomeAction([FromBody]string param1, [FromBody]IEnumerable<SomeType> param2, [FromBody]IEnumerable<SomeType> param3)
{
//param1 and param2 and param3 are null
}
客户端:
$.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);
}
}
);
推荐答案
使用新版本时,需要明确说明预期绑定模型的对象和位置.
With the new version actions need to be explicit about what and where they expected to bind models from.
创建一种模式以保存所有必需的数据
Create a mode to hold all the required data
public class SomeActionModel {
public string param1 { get; set; }
public IEnumerable<SomeType> param2 { get; set; }
public IEnumerable<SomeType> param3 { get; set; }
}
更新操作以期望来自请求正文的数据
Update the action to expect the data from the body of the request
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);
}
客户端还应该以正确的格式发送数据
The client should also send the data in the correct format
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);
}
});
这篇关于使用post方法将多个参数发送到asp.net core 3 mvc操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!