问题
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