我收到以下错误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
非常感谢任何帮助: - )
答案 0 :(得分:3)
两个选项:
答案 1 :(得分:0)
像下面这样使用并导入 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");
}
}