MVC5 EditorForの便利な使い方(ICollectionをバインド)

モデル: Models\Hoge.cs

public class Hoge {
    public virtual ICollection<Fuga> FugaCollection { get; set; }
}

モデル: Models\Fuga.cs

public class Fuga {
    public string FugaFuga { get; set; }
}

コントローラー: Controllers\HogeController.cs

[HttpPost]
public ActionResult Create(Hoge hoge) {
    // Do something
}

ビュー(テンプレート): Views\Hoge\EditorTemplates\Fuga.cshtml
(共通の場合はShared配下でよい)

@model Sample.Models.Fuga
@Html.TextBoxFor(model => model.FugaFuga) @* ただの例 任意の内容を記述する *@

ビュー(メイン): Views\Hoge\Create.cshtml

@model Sample.Models.Hoge

@* その1 ICollection<T>を渡す(テンプレート側のモデルの型はコレクションではない) *@
@Html.EditorFor(model => model.FugaCollection)

@* その2 テンプレート名を指定したい場合はプレフィックスを指定する *@
@{int idx = 0}
foreach (var item in Model.FugaCollection) {
    @Html.EditorFor(model => item, "Fuga", "FugaCollection[" + idx++ + "]")
}

テンプレート部分の内容をajax等で動的に追加削除する場合等はさらにBeginCollectionItemを組み合わせる。

MVC Series Part 1: Dynamically Adding Items Part 1 | //InterKnowlogy/ Blogs
http://blogs.interknowlogy.com/2014/08/01/mvc-series-part-1-dynamically-adding-items-part-1/

GitHub - danludwig/BeginCollectionItem: This Html Helper leverages the default model binder in ASP.NET MVC 2 and higher to materialize viewmodel collection properties from an HTTP POST.
https://github.com/danludwig/BeginCollectionItem