Web アプリケーションに ASP.NET MVC を使用し、クライアント側フレームワークに jQuery を使用していると仮定します。
次のようなモデルがあると仮定しましょう。
public class Gift
{
public string Name { get; set; }
public double Price { get; set; }
}
最初のアクションとデータは次のようになります。
public ActionResult Index()
{
var initialData = new[] {
new Gift { Name = "Tall Hat", Price = 39.95 },
new Gift { Name = "Long Cloak", Price = 120.00 },
};
return View(initialData);
}
一方、あなたの見解は次のようになります。
<h2>Gift List</h2>
What do you want for your birthday?
<% using(Html.BeginForm()) { %>
<div id="editorRows">
<% foreach (var item in Model)
Html.RenderPartial("GiftEditorRow", item);
%>
</div>
<input type="submit" value="Finished" />
<% } %>
ギフト エディターの部分ビューは次のようになります。
<div class="editorRow">
<% using(Html.BeginCollectionItem("gifts")) { %>
Item: <%= Html.TextBoxFor(x => x.Name) %>
Value: $<%= Html.TextBoxFor(x => x.Price, new { size = 4 }) %>
<% } %>
</div>
重要なのは、ASP.NET MVC の標準ではない「BeginCollectionItem」ヘルパー メソッドです。可変長モデルのいくつかのキーを生成します。後でファイルへのリンクを追加します。ハンドラーは次のようになります。
[HttpPost]
public ActionResult Index(IEnumerable<gift> gifts)
{
// To do: do whatever you want with the data
}
このアプローチでは、テキストボックスに値が入力されたギフトのリストを取得します。もう 1 つアイテムを追加するには、このビューに ajax リクエストを送信する必要があります。
ソース: http://blog.stevensanderson.com/2010/01/28/editing-a-variable-length-list-aspnet-mvc-2-style/
ダウンロード: http://blog.codeville.net /blogfiles/2010/January/ListEditorDemo.zip