c# - Core Web Api - 错误:动作从请求正文绑定了多个参数
问题描述
[ApiController]
[Route("test")]
public class AdminController : ControllerBase
{
[HttpPost]
public IActionResult Create(CarModel car, int[] customers, int model)
{
var item = new Car()
{
Name = car.Name,
Price = car.Price
};
repository.Create(item, customers, model)
return Ok(item);
}
}
车类
public int Id { get; set; }
public string Name{ get; set; }
public int Price{ get; set; }
汽车模型
public int Id { get; set; }
public string Name{ get; set; }
public int Price{ get; set; }}
我可以将“客户”和“模型”参数添加到我的“汽车”类中。但我不想在我的“汽车”类中添加“客户”和“模型”参数
我怎样才能以其他方式解决这个问题。
解决方案
如果您从请求正文中发布所有这些输入参数,则必须创建 ViewModel:
public class CarViewModel
{
public CarModel car {get; set;}
public int[] customers {get; set;}
public int model {get; set;}
}
但我认为你不需要所有这些属性,你可以合并一些。
改变你的行动:
public IActionResult Create(CarViewModel model)
//or you can try, I don't know how you call your action
public IActionResult Create([FromBody] CarViewModel model)
将视图中的模型替换为:
@model CarViewModel
并修复您的视图控件数据绑定
推荐阅读
- android - 无法启动 API 29 模拟器 (Android 10)
- javascript - 在 Jquery 中使用 Div 元素选择同级的问题
- python - 为什么 Google Cloud KMS 会为相同的输入文本生成不同的加密密文?
- r - 数据框列表,但每个列表项都有一个 df 和另一个值,无法让 bind_rows() 组合它们
- docker - 在没有暴露端口的情况下,容器如何通过 python 与另一个通信?
- python - 如何在 matplotlib 中为多个图设置规范?
- graphics - GLSL(vulkan 方言)模运算符导致奇怪的行为
- google-cloud-platform - 我们不鼓励在 Google Kubernetes Engine (GKE) 中进行基本身份验证
- salesforce-lightning - 如何从js获取账户ID?lwc
- python - 在 VS Code 中以交互方式使用 Python(*.py 文件)时是否可以显示/探索变量值?