4

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?

Kahbazi
  • 14,331
  • 3
  • 45
  • 76
John
  • 716
  • 1
  • 7
  • 24

1 Answers1

5

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)
Juan Rojas
  • 8,711
  • 1
  • 22
  • 30
adem caglin
  • 22,700
  • 10
  • 58
  • 78
  • Ancient thread - I know, sorry, but is there ANY way to make use of tag helpers and post json contenttype data? – Dynde Feb 08 '18 at 15:50
  • @Dynde you can write your own `JsonFormTagHelper` ,to append the javascript before or after `` , – John Apr 04 '18 at 06:13