ASP.NET MVC 3 で IEnumerable<T> を編集するにはどうすればよいですか?
-
26-09-2019 - |
質問
次のタイプがあるとします
public class SomeValue
{
public int Id { get; set; }
public int Value { get; set; }
}
public class SomeModel
{
public string SomeProp1 { get; set; }
public string SomeProp2 { get; set; }
public IEnumerable<SomeValue> MyData { get; set; }
}
タイプの編集フォームを作成したい SomeModel
これには通常のテキストフィールドが含まれます SomeProp1
そして SomeProp2
次に、それぞれのテキストフィールドを含むテーブル SomeValue
の中に SomeModel.MyData
コレクション。
これはどのように行われるのでしょうか?値はどのようにしてモデルにバインドされるのでしょうか?
現在、各値のテキストフィールドを表示するフォームがありますが、それらはすべて同じ名前と同じIDを持っています。これは明らかに有効な HTML ではないため、MVC が値をマッピングし直すことができなくなります。
解決
これはエディター テンプレートを使用して行います。このようにして、フレームワークがすべてを処理します (入力フィールドの適切な名前付けから、ポストアクションでの値の適切なバインドまで)。
コントローラ:
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" />
<% } %>
そして最後にエディター テンプレート (~/Views/Home/EditorTemplates/SomeValue.ascx
) の各要素に対して自動的に呼び出されます。 MyData
コレクション:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<MyApp.Models.SomeValue>" %>
<div>
<%= Html.TextBoxFor(x => x.Id) %>
<%= Html.TextBoxFor(x => x.Value) %>
</div>
他のヒント
IList
IEnumerable を実装しているので、次のようにモデルを変更できます。
public class SomeModel {
public string SomeProp1 { get; set; }
public string SomeProp2 { get; set; }
public IList<SomeValue> MyData { get; set; }
}
使用できます IModelBinder
インターフェイスを使用して、特定のモデルのバインダーを作成します。それにはいくつかの方法があります。作成できます EditorFor
ループするモデルの cshtml SomeValue
適切な ID などをリストして出力します。次に、あなたの中で ModelBinder
実装すると、ID を読み取り、適切にバインドします。しばらくしたら動作サンプルを投稿できます。