2009年11月11日水曜日

[ASP.NET MVC] リストのモデルバインド

ASP.NET MVCでモデルバインドが便利っぽいような不便っぽいような。
新規にリストの値をバインドするなら問題ないのですよ。

Model
  1. Public Class PrivateInfo  
  2.     Public Name As String  
  3.     Public History As List(Of History)  
  4. End Class  
  5.   
  6. Public Class History  
  7.     Public eventDate As DateTime  
  8.     Public Score As Int32  
  9.     Public Cost As Int32  
  10. End Class  


View
  1. <%  
  2. For each item In Model.History  
  3.   Dim index As Integer = Model.History.IndexOf(item)  
  4. %>  
  5. <%=Html.TextBox(String.Format("History[{0}].Score", index), item.Score)%>  
  6. <%=Html.TextBox(String.Format("History[{0}].Cost", index), item.Cost)%>  
  7.   
  8. <% Next%>  


ところがですね、すでにある程度の値が入っているリストに画面でeventDateを設定させようとしてUpdateModelすると、ScoreとCostが消えちゃうのです。
View
  1. <%  
  2. For each item In Model.History  
  3.   Dim index As Integer = Model.History.IndexOf(item)  
  4. %>  
  5. <%=Html.TextBox(String.Format("History[{0}].eventDate", index), item.eventDate)%>  
  6.   
  7. <% Next%>  


Controller
  1. <AcceptVerbs(HttpVerbs.Post)> _  
  2. Public Function Input2(ByVal collection As FormCollection) As ActionResult  
  3.     Dim model As Models.PrivateInfo = Session("PrivateInfo")  
  4.   
  5.     UpdateModel(model)  
  6.   
  7.     Return View(model)  
  8. End Function  



そこまでやってくれないんですね。
対策としては、その他の項目もPostしちゃうと。

View
  1. <%  
  2. For each item In Model.History  
  3.   Dim index As Integer = Model.History.IndexOf(item)  
  4. %>  
  5. <%=Html.TextBox(String.Format("History[{0}].eventDate", index), item.eventDate)%>  
  6. <%=Html.Hidden(String.Format("History[{0}].Score", index), item.Score)%>  
  7. <%=Html.Hidden(String.Format("History[{0}].Cost", index), item.Cost)%>  
  8.   
  9. <% Next%>  



イケテナイ。
自分でマージするか

0 件のコメント: