ASP.NET Core 1.0 POST IEnumerable to controller

后端 未结 2 1264
既然无缘
既然无缘 2020-12-19 12:40

I have an action that returns a model to the View which is IEnumerable. In the view I loop through the list using foreach. T type has a property called

相关标签:
2条回答
  • 2020-12-19 12:53

    The problem was @model IEnumerable<Product> in the view. I changed that to List and use instead a for loop:

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

    SAVE

    0 讨论(0)
  • 2020-12-19 13:12

    It finally boils down to the serialization format that MVC understands for form posts (ex: application/x-www-form-urlencoded). So whenever you use TagHelpers or HtmlHelpers make sure that you try to render the form in the following way:

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


    Action parameter: Manufacturer manufacturer where Manufacturer type is like below:

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

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


    Action parameter: IEnumerable<string> states
    Request format1: states=wa&states=mi&states=ca
    Request format2: states[0]=wa&states[1]=mi&states[2]=ca


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

    0 讨论(0)
提交回复
热议问题