2016-07-14 92 views
4

我有一個操作,返回一個模型到視圖這是IEnumerable<T>。在視圖中,我使用foreach循環訪問列表。 T型有一個稱爲金額的屬性。ASP.NET核心1.0 POST IEnumerable <T>到控制器

現在,當我點擊SAVE按鈕時,我想POST模型(IEnumerable)爲一個動作。 IEnumerbale項目,其屬性Amount應包含正確的值。

enter image description here

當我提交它,在行動中,型號爲NULL。

爲了測試IEnumerable<T>IEnumerable<Produt>

public class Product 
{ 

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

視圖顯示產品:

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

控制器交動作:

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

    } 

回答

2

的問題是在視圖@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> 
    } 

SAVE

1

它最終歸結到MVC理解爲形式的職位(如序列化格式:應用程序/ x-WWW - 形式進行了urlencoded)。所以每當你使用TagHelpersHtmlHelpers確保您嘗試呈現形式以下列方式:

操作參數: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
請求FORMAT2:states[0]=wa&states[1]=mi&states[2]=ca


操作參數:Dictionary<string, string> states
請求格式:states[wa]=washington&states[mi]=michigan&states[ca]=california