asp.net-core - 如何在 MVC Core 中绑定(bind)数组

标签 asp.net-core asp.net-core-mvc model-binding

我尝试在 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/

相关文章:

model-view-controller - BindModel() 实现应该做什么?

c# - ASP.NET MVC 本地化或更改默认模型绑定(bind)错误消息

docker - ${DOCKER_REGISTRY-} 在哪里设置

asp.net-core - 存储/验证存储在 .net core api 中的 HttpOnly cookie 中的 JWT token

asp.net-mvc - 返回 ASP.Net Core MVC 中的上一页

c# - 如何在 ASP.NET MVC 6 (ASP.NET Core) 中获取 returnUrl AccessDeniedPath

ASP.NET-MVC2 : Why does TryUpdateModel ignore properties after the second level of the object model tree?

linux - 使用 mono 在 Centos 中部署 ASP.net

c# - 注册类时依赖注入(inject)错误 : Unable to resolve service for type while attempting to activate,

ASP.NET Core 发布错误 : An error occurred while starting the application