How to bind an Array in MVC Core

主宰稳场 提交于 2019-12-06 05:51:17

问题


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; }
}

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

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


回答1:


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>

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

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

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

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


来源:https://stackoverflow.com/questions/38929009/how-to-bind-an-array-in-mvc-core

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!