C# ASP.NET 核心无法绑定到 'Microsoft.AspNetCore.Http.FormCollection' 类型的模型

C# ASP.NET Core Cannot bind to a model of type 'Microsoft.AspNetCore.Http.FormCollection'

我收到以下错误 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);
}

在模型 Test 中,我正在使用 [Decimal] 属性,该属性与 ModelBinder 结合使用,但无论如何我都不想绑定到表单,我只想绑定到模型,所以我有点困惑为什么会出现此消息。

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

C# ASP.NET Core ModelBinder not Updating Model

任何帮助将不胜感激:-)

两个选项:

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

像下面那样使用并导入 using Microsoft.AspNetCore.Http; 命名空间。

 [HttpPost]
        public ActionResult Create(IFormCollection foFormCollection)
        {
            try
            {
                UserDataContext DBContext = new UserDataContext();
                Users Users = new Users();

                Users.EmpName = foFormCollection["EmpName"].ToString();
                Users.UserPassword = foFormCollection["UserPassword"].ToString();
                Users.flgIsActive = string.IsNullOrEmpty(foFormCollection["ActiveStatus"]) ? false : true;
                Users.EmployeeId = foFormCollection["EmployeeId"].ToString() == "0" ? 0 : Convert.ToInt64(foFormCollection["EmployeeId"]);

                Int64 Success = DBContext.addEditUser(Users)
                return RedirectToAction("pagename");
            }
            catch
            {
                return RedirectToAction("pagename");
            }
        }