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?

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

2 Comments

Ancient thread - I know, sorry, but is there ANY way to make use of tag helpers and post json contenttype data?
@Dynde you can write your own JsonFormTagHelper ,to append the javascript before or after </form> ,

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.