如何在MVC Core中绑定阵列 [英] How to bind an Array in MVC Core

查看:114
本文介绍了如何在MVC Core中绑定阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I try to bind an object like this in a 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不会被绑定,而这是我提交的数据:

Is that possible? How do i design the form? I try a few times but the property MoneyCosts won't be bind , and this is the data i submited:

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

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

I saw a modelbinder called ArrayModelBinder<T> , how do i use it?

推荐答案

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

If you use x-www-url-formencoded content type then try to change(if possible) your post data like below:

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内容类型,则您的数据应如下所示:

If you use json content type, your data should be something like this:

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

对于json请求,您应该在操作方法中使用FromBody.

in the case of json request you should use FromBody in action method.

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

这篇关于如何在MVC Core中绑定阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆