【发布时间】:2018-11-14 23:59:19
【问题描述】:
我最初在 GitHub 上发布了这个问题:https://github.com/aspnet/Mvc/issues/8723
这里有一个 GitHub 存储库,其中重现了该问题: https://github.com/Costo/aspnetcore-binding-bug
我正在使用 ASP.NET Core 2.2 Preview 3。
在“子”模型数组的属性上使用自定义模型绑定器(带有 [ModelBinder] 属性)时,请求的模型绑定阶段进入无限循环。看这个截图:
如果在顶级模型属性上使用自定义模型绑定器效果很好,但我想了解为什么它在子模型数组中使用时不起作用。对此的任何帮助将不胜感激。
谢谢!
这是模型、控制器、视图和自定义绑定器的代码:
模型:
public class TestModel
{
public TestInnerModel[] InnerModels { get; set; } = new TestInnerModel[0];
[ModelBinder(BinderType = typeof(NumberModelBinder))]
public decimal TopLevelRate { get; set; }
}
public class TestInnerModel
{
public TestInnerModel()
{
}
[ModelBinder(BinderType = typeof(NumberModelBinder))]
public decimal Rate { get; set; }
}
自定义模型绑定器(特意简化为没什么特别的):
public class NumberModelBinder : IModelBinder
{
private readonly NumberStyles _supportedStyles = NumberStyles.Float | NumberStyles.AllowThousands;
private DecimalModelBinder _innerBinder;
public NumberModelBinder(ILoggerFactory loggerFactory)
{
_innerBinder = new DecimalModelBinder(_supportedStyles, loggerFactory);
}
/// <inheritdoc />
public Task BindModelAsync(ModelBindingContext bindingContext)
{
return _innerBinder.BindModelAsync(bindingContext);
}
}
控制器:
public class HomeController : Controller
{
public IActionResult Index()
{
return View(new TestModel
{
TopLevelRate = 20m,
InnerModels = new TestInnerModel[]
{
new TestInnerModel { Rate = 2.0m },
new TestInnerModel { Rate = 0.2m }
}
});
}
[HttpPost]
public IActionResult Index(TestModel model)
{
return Ok();
}
}
剃刀视图:
@model TestModel;
<form asp-controller="Home" asp-action="Index" method="post" role="form">
<div>
<input asp-for="@Model.TopLevelRate" type="number" min="0" step=".01" />
</div>
<div>
@for (var i = 0; i < Model.InnerModels.Length; i++)
{
<input asp-for="@Model.InnerModels[i].Rate" type="number" min="0" step=".01" />
}
</div>
<input type="submit" value="Go" />
</form>
【问题讨论】:
标签: asp.net-core-mvc