2012-03-27 63 views
0

我有一個模型,其中包含一個自定義類型的列表。如何在HttpPost的模型中保留List對象?

我希望這種類型的數據在作爲HttpPost調用控制器提交模型時被傳回。

但是,它似乎沒有做我想要的。我目前在Passing IEnumerable or list Model to Controller using HttpPost以上,但我遇到了問題。

我控制器的方法:

[HttpPost] 
    public ActionResult UpdateStock(int id, ProductModel model) 
    { 
     return View("UpdateStock", model); 
    } 

現在,查看是這樣的(修剪):

@using (Html.BeginForm()) 
{ 
<div> 
    <p> 
    <input type="submit" value="Save" /> 
    </p> 

    @Html.HiddenFor(m => m.ProductNo) 

    <div class = "title"> 
    @Html.LabelFor(m => m.ProductName) 
    @Html.EditorFor(m => m.ProductName) 
    </div> 

      @for (int i = 0; i < Model.Stock.Count; i++) 
      { 
       var item = Model.Stock[i]; 
       <div class="editor-field"> 
        <input type="text" name="Model.Stock[@i].Key" 
         value="@item.Key" /> 
       </div> 
       <div class="editor-field"> 
        <input type="text" name="Model.Stock[@i].Value" 
         value="@item.Value" /> 
       </div> 
      } 
} 

我的問題是,它似乎@Html.EditorFor()<input type=.../>標籤似乎不互相打好。如果我像上面那樣,那麼ProductNo和其他使用@Html方法的屬性將不會被傳遞給模型。

任何意見非常讚賞。

回答

2

我會簡單地使用編輯器模板:

型號:

public class ProductModel 
{ 
    public string ProductNo { get; set; } 
    public string ProductName { get; set; } 
    public IEnumerable<Stock> Stocks { get; set; } 
} 

public class Stock 
{ 
    public string Key { get; set; } 
    public string Value { get; set; } 
} 

控制器:

public class HomeController: Controller 
{ 
    public ActionResult Index() 
    { 
     var model = new ProductModel 
     { 
      ProductNo = "123", 
      ProductName = "p name", 
      Stocks = new[] 
      { 
       new Stock { Key = "key1", Value = "value1" }, 
       new Stock { Key = "key2", Value = "value2" }, 
      } 
     }; 
     return View(model); 
    } 

    [HttpPost] 
    public ActionResult Index(ProductModel model) 
    { 
     ... 
    } 
} 

查看:

@model ProductModel 
@using (Html.BeginForm()) 
{ 
    <p> 
     <input type="submit" value="Save" /> 
    </p> 

    @Html.HiddenFor(m => m.ProductNo) 

    <div class = "title"> 
     @Html.LabelFor(m => m.ProductName) 
     @Html.EditorFor(m => m.ProductName) 
    </div> 

    @Html.EditorFor(x => x.Stocks) 
} 

,然後定義自定義編輯模板對於庫存類型(~/Views/Shared/EditorTemplates/Stock.cshtml):

@model Stock 
<div class="editor-field"> 
    @Html.EditorFor(x => x.Key) 
</div> 
<div class="editor-field"> 
    @Html.EditorFor(x => x.Value) 
</div> 
+0

感謝您的回覆!這很好。 – TZHX 2012-03-27 12:45:35