C# ASP.NET Core 无法绑定到“Microsoft.AspNetCore.Http.FormCollection”类型的模型

igg*_*web 2 c# model-binding formcollection asp.net-core-mvc

我收到以下错误 An unhandled exception occurred while processing the request. InvalidOperationException: The 'Microsoft.AspNetCore.Mvc.ModelBinding.Binders.FormCollectionModelBinder' cannot bind to a model of type 'Microsoft.AspNetCore.Http.FormCollection'. Change the model type to 'Microsoft.AspNetCore.Http.IFormCollection' instead.

这是我使用以下代码的时候:

[ValidateAntiForgeryToken]
[HttpPost]
public IActionResult Index(Test test, FormCollection formCollection)
{        
    var feesAmountArray = new List<string>();

    foreach (var item in formCollection.Keys.Where(k => k.StartsWith("FeesAmount-")))
    {
        feesAmountArray.Add(formCollection[item].ToString().TrimEnd(','));
    }

    var feesAmount = string.Join(",", feesAmountArray);

    if (ModelState.IsValid)
    {
    }

    return View(test);
}
Run Code Online (Sandbox Code Playgroud)

在模型中,Test我使用了一个[Decimal]与 a 结合使用的属性ModelBinder,但无论如何我都不想绑定到表单,我只想绑定到模型,所以我有点困惑为什么这条消息是呈现自己。

可以在以下位置找到与 ModelBinder 相关的代码:

C# ASP.NET Core ModelBinder 不更新模型

任何帮助将非常感激 :-)

Ric*_*res 7

两种选择:

  1. 将您的参数更改为 IFormCollection
  2. 删除它,而是通过 HttpContext.Form 访问它