我尝试在 Action 中绑定(bind)这样的对象
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
不会被绑定(bind),这是我提交的数据:Year=2016
Moneh=8
MoneyCosts.Title=ABC
MoneyCosts.Cost=100
MoneyCosts.Title=DEF
MoneyCosts.Cost=200
我看到了一个名为
ArrayModelBinder<T>
的模型绑定(bind)器。 ,我该如何使用它?
最佳答案
如果您使用 x-www-url-formencoded
内容类型然后尝试更改(如果可能)您的帖子数据,如下所示:
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)
关于asp.net-core - 如何在 MVC Core 中绑定(bind)数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38929009/