更新:
您必须为 IGrouping 编写自己的 EditorTemplate。
IGrouping 的 EditorTemplate 示例:
模型:
public class Row
{
public Row()
{
}
public Row(string key, int value)
{
Key = key;
Value = value;
}
public int Value { get; set; }
public string Key { get; set; }
}
控制器:
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "Welcome to ASP.NET MVC!";
IEnumerable<Row> dict = new[] { new Row("1", 1), new Row("1", 2), new Row("1", 3), new Row("2", 2), new Row("2", 3), new Row("2", 4) };
var grouped = dict.GroupBy(c => c.Key).First();
//var grouplist = grouped.Select(c => new KeyValuePair<string, IEnumerable<int>> (c.Key, c.Select(b=>b.Value)));
return View(grouped);
}
public ActionResult Post(IEnumerable<Row> Model)
{
return null;
}
}
查看索引:
@model IGrouping<string, MvcApplication1.Models.Row>
@{
ViewBag.Title = "Home Page";
}
@using(Html.BeginForm("Post", "Home", FormMethod.Post))
{
@Html.EditorForModel("IGrouping")
<button type="submit">Submit</button>
}
EditorTemplate IGrouping.cshtml:
@model IGrouping<string, MvcApplication1.Models.Row>
@{
@Html.DisplayFor(m => m.Key)
int i = 0;
foreach (var pair in Model.Select(c => c))
{
@Html.Hidden(string.Format("Model[{0}].Key", i), pair.Key)
@Html.TextBox(string.Format("Model[{0}].Value", i), pair.Value)
i++;
}
}
More about binding Collections you can read there:Hancelman's blog