あなたはエディタテンプレートを使用します。このようにして、フレームワークは、入力フィールドの名前を正しく指定することから、ポストアクションで値を適切にバインドすることに至るまで、すべてを処理します。
コントローラー:
public class HomeController : Controller
{
public ActionResult Index()
{
// In the GET action populate your model somehow
// and render the form so that the user can edit it
var model = new SomeModel
{
SomeProp1 = "prop1",
SomeProp2 = "prop1",
MyData = new[]
{
new SomeValue { Id = 1, Value = 123 },
new SomeValue { Id = 2, Value = 456 },
}
};
return View(model);
}
[HttpPost]
public ActionResult Index(SomeModel model)
{
// Here the model will be properly bound
// with the values that the user modified
// in the form so you could perform some action
return View(model);
}
}
ビュー(~/Views/Home/Index.aspx
):
<% using (Html.BeginForm()) { %>
Prop1: <%= Html.TextBoxFor(x => x.SomeProp1) %><br/>
Prop2: <%= Html.TextBoxFor(x => x.SomeProp2) %><br/>
<%= Html.EditorFor(x => x.MyData) %><br/>
<input type="submit" value="OK" />
<% } %>
、自動的にMyData
コレクションの各要素に対して呼び出されます最終的にはエディタテンプレート(~/Views/Home/EditorTemplates/SomeValue.ascx
):
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<MyApp.Models.SomeValue>" %>
<div>
<%= Html.TextBoxFor(x => x.Id) %>
<%= Html.TextBoxFor(x => x.Value) %>
</div>
あなたは答えが既に良いので、私は今それを投稿しないだろうと思う:)私はあなたが簡単にリストをバインドできるか分からなかった。おかげで – Buildstarted
MVC3のためにそれは剃刀を使用する方が良いですか? – arame3333