如何在 MVC Core 中绑定数组

How to bind an Array in MVC Core

我尝试在 Action 中绑定这样的对象

public class MonthDataViewModel
{
    public int Year { get; set; }
    public int Month { get; set; }
    public IEnumerable<MoneyDataItemViewModel> MoneyCosts { get; set; }  
}
public class MoneyDataItemViewModel
{
    public string Title { get; set; }
    public decimal Cost { get; set; }
}

这可能吗?我如何设计表格? 我尝试了几次,但 属性 MoneyCosts 不会绑定,这是我提交的数据:

Year=2016
Moneh=8
MoneyCosts.Title=ABC
MoneyCosts.Cost=100
MoneyCosts.Title=DEF
MoneyCosts.Cost=200

我看到了一个名为 ArrayModelBinder<T> 的模型绑定器,我该如何使用它?

如果您使用 x-www-url-formencoded 内容类型,请尝试更改(如果可能)您的 post 数据,如下所示:

Year=2016&Month=8&MoneyCosts[0].Title=ABC&MoneyCosts[0].Cost=100&MoneyCosts[1].Title=DEF&MoneyCosts[1].Cost=200

How do i design the form?

<form asp-controller="Home" asp-action="AccountName" method="post">
    <input type="text" name="Year" />
    <input type="text" name="Month" />
    @for(var i = 0; i < count; i++)
    {
        <input type="text" name="@("MoneyCosts["+ i + "].Title")" />
        <input type="text" name="@("MoneyCosts["+ i + "].Cost")" />
    }
    <input type="submit" value="Submit" />
</form>

如果您使用 json 内容类型,您的数据应该是这样的:

{"Year": "2016", "Month":"8", "MoneyCosts":[{"Title":,"ABC"}, ...]}

json 请求的情况下,您应该在操作方法中使用 FromBody

    [HttpPost]
    public IActionResult ActionName([FromBody]MonthDataViewModel model)