gpt4 book ai didi

c# - 使用post方法将多个参数发送到asp.net core 3 mvc Action

转载 作者:行者123 更新时间:2023-12-05 06:23:19 24 4
gpt4 key购买 nike

使用 http post 方法向 asp.net mvc core 3 操作发送具有多个参数的 ajax 请求时出现问题。参数不绑定(bind)。在点网框架 asp.net web api 中有类似的限制,但在 asp.net mvc 操作中没有。我想知道在 asp.net core 3 mvc 中是否有解决这个问题的方法或者这是新的限制? 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);
}
}
);

最佳答案

在新版本中,操作需要明确说明他们希望从什么地方绑定(bind)模型。

创建一个模式来保存所有需要的数据

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);
}
});

引用 Model Binding in ASP.NET Core

关于c# - 使用post方法将多个参数发送到asp.net core 3 mvc Action ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58502744/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com