0

我有一堆項目,我已經分組了Header。如何顯示IEnumerable <IGrouping <字符串,模型>>與編輯器模板

我想在頁面上顯示它們,標題文本後面跟着每個單獨項目的編輯器模板。

我嘗試使用嵌套的模板如下:

主頁:

@Html.EditorFor(x => x.GroupedItems, "ListofGrouping"); 

ListofGrouping編輯模板:

@model IList<IGrouping<string, Model>> 
@for(int i = 0; i < Model.Count(); i++) 
{ 
    @Html.EditorFor(x => x[i],"IGrouping") 
} 

IGrouping編輯模板:

@model IGrouping<string, Model> 

@Html.DisplayFor(x => x.Key) 
@Html.EditorForModel() 

這工作到最後一行。我得到所有標題值,但不顯示單個項目。

如果我不能以這種方式工作,我將只使用數據網格並在那裏進行分組,但我認爲這應該是可能的在MVC3。

回答

0

更新: 您必須爲IGrouping編寫您自己的EditorTemplate。 EditorTemplate的

樣品爲IGrouping: 型號:

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++; 
    } 
} 

更多關於綁定集合,你可以從中讀到:Hancelman's blog

+0

不能編譯 – Kelly

+0

你可以顯示什麼是你的「收藏」模板? –

+0

這實際上是一個內置的模板,它應該可以使用或不使用「Collection」參數。 – Kelly

0

記住IGrouping也是IEnumerable的。因此,而不是使用@Html.EditorForModel(),枚舉項目。

@model IGrouping<string, Model> 

@Html.DisplayFor(x => x.Key) 
foreach (var grp in Model) 
{ 
    @Html.EditorFor(model => grp) 
} 
相關問題