ASP.NET Core 1.0 POST IEnumerable <T> for the controller

I have an action that returns the model in the view that is IEnumerable<T>. In the view, I am browsing the list using foreach. Type T has the Sum property.

Now, when I click the button SAVE, I want the POST model (IEnumerable) on the action. IEnumerbale elements, their properties Amountmust contain the correct values.

enter image description here

When I submit it, in action the model is null.

For testing IEnumerable<T>thereIEnumerable<Produt>

public class Product
{

    public string Title { get; set; }
    public int Amount { get; set; }
}

View displayed products:

 @model IEnumerable<Product>


 <form asp-controller="Home" asp-action="Order" method="post" role="form">
       @foreach (var product in Model)
       {
            <div>
                  <span>@product.Title</span>
                  <input asp-for="@product.Amount" type="text">
            </div>
       }
  <button type="submit">SAVE</button>         

 </form>

Actions with the controller:

    [HttpPost]    
    public async Task<IActionResult> Order(IEnumerable<Product> model)
    {

    }
+4
source share
2 answers

@model IEnumerable<Product> . for:

@model List<Product>


<form asp-controller="Home" asp-action="Order" method="post" role="form">
   @for (int i = 0; i < Model.Count(); i++)
   {
        <div>
              <span>@Model[i].Title</span>
              <input asp-for="@Model[i].Amount" type="text">
        </div>
   }

+2

, , MVC (: application/x-www-form-urlencoded). , TagHelpers HtmlHelpers, , :

: IEnumerable<Product> products
: [0].Title=car&[0].Amount=10.00&[1].Title=jeep&[1].Amount=20.00


: Manufacturer manufacturer Manufacturer :

public class Manufacturer
{
    public string Name { get; set; }
    public List<Product> Products { get; set; }
}

public class Product
{
    public string Title { get; set; }
    public int Amount { get; set; }
}

: Name=FisherPrice&Products[0].Title=car&Products[0].Amount=10.00&Products[1].Title=jeep&Products[1].Amount=20.00


: IEnumerable<string> states
1: states=wa&states=mi&states=ca
2: states[0]=wa&states[1]=mi&states[2]=ca


: Dictionary<string, string> states
: states[wa]=washington&states[mi]=michigan&states[ca]=california

+1

All Articles