【发布时间】:2018-02-14 16:06:36
【问题描述】:
我收到以下错误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
任何帮助将不胜感激:-)
【问题讨论】:
-
如果您不希望
formCollection值成为模型绑定的一部分,您希望它是什么? -
主表单绑定到
Test模型,但是表单可以包含一些由jQuery创建的动态字段,所以我主要需要验证基础Test模型,另外检查动态字段生成的Test模型中不存在。 -
我添加了额外的代码来满足 FormCollection 的需求。
-
好的,下一个问题:为什么你不能听从错误的建议而只使用
IFormCollection而不是FormCollection? -
不确定是否有理由降低标记。问这个问题的原因是我不明白这个错误。我只对
Test模型中的某些属性使用模型绑定,我没有对FormCollection使用任何模型绑定,因此造成了混乱。
标签: c# asp.net-core-mvc model-binding formcollection