我正在尝试利用我正在循环的集合的HTML帮助程序,但我不知道该怎么做。更具体地说,在下面的代码中,我正在尝试为modulegroup.Name和modulegroup.HtmlDivId创建HTML帮助程序(Html.EditorFor)。怎么办呢?
@foreach (var modulegroup in Model.SelectedPage.ModuleGroupCollection)
{
<div>
@modulegroup.Name
</div>
<div>
@modulegroup.HtmlDivId
</div>
foreach (var module in modulegroup.ModuleCollection)
{
<div>
@module.Name
</div>
<div>
@if(module.LockedBy != null) {
@module.LockedBy.Name
}
</div>
}
}
答案 0 :(得分:0)
@{
int modulegroupIndex = 0;
int moduleIndex = 0;
}
@foreach (var modulegroup in Model.SelectedPage.ModuleGroupCollection)
{
<div>
@Html.EditorFor(model => model.SelectedPage.ModuleGroupCollection[modulegroupIndex].Name)
</div>
<div>
@Html.EditorFor(model => model.SelectedPage.ModuleGroupCollection[modulegroupIndex].HtmlDivId)
</div>
foreach (var module in modulegroup.ModuleCollection)
{
<div>
@Html.EditorFor(model => model.SelectedPage.ModuleGroupCollection[modulegroupIndex].ModuleCollection[moduleIndex].Name)
</div>
<div>
@if(module.LockedBy != null) {
@Html.EditorFor(model => model.SelectedPage.ModuleGroupCollection[modulegroupIndex].ModuleCollection[moduleIndex].LockedBy.Name)
}
</div>
moduleIndex++;
}
modulegroupIndex++;
}
答案 1 :(得分:0)
我相信你正在寻找EditorTemplates与HTML Helpers。以下是关于该主题的一些阅读:http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-4-custom-object-templates.html
我通常将视图特定模板放在与其相关的视图文件夹的子文件夹“EditorTemplates”中。对于可重复使用的模板,我会做同样的事情但只是共享文件夹中的“EditorTemplates”文件夹。
那就是说,这里有一个例子,在下面的示例模型&amp;控制器。注意,这将输出以下内容:
first
one
collection1
jonah jameson
collection2
spidey
控制器:
public ActionResult Index()
{
var model = new SampleViewModel
{
SomeGroup = new List<ModuleGroupCollection>
{
new ModuleGroupCollection
{
HtmlDivId = "one",
Name = "first",
SomeCollection = new List<ModuleCollection>
{
new ModuleCollection()
{
Name = "collection1",
LockedBy = "jonah jameson"
},
new ModuleCollection()
{
Name = "collection2",
LockedBy = "spidey"
}
}
}
}
};
return View("Index", model);
}
模型:
public class SampleViewModel
{
public IEnumerable<ModuleGroupCollection> SomeGroup { get; set; }
}
public class ModuleGroupCollection
{
public string Name { get; set; }
public string HtmlDivId { get; set; }
public IEnumerable<ModuleCollection> SomeCollection { get; set; }
}
public class ModuleCollection
{
public string Name { get; set; }
public string LockedBy { get; set; }
}
视图,请注意编辑器模板的用法:
@model StackQuestions.Models.SampleViewModel
@foreach (var item in Model.SomeGroup) {
@Html.EditorFor(x=>item)
foreach (var module in item.SomeCollection)
{
@Html.EditorFor(x=>module)
}
}
模块集合编辑器模板:
@model StackQuestions.Models.ModuleCollection
<div>
@Model.Name
</div>
<div>
@if (Model.LockedBy != null)
{
@Model.LockedBy
}
</div>
模块组集合编辑器模板:
@model StackQuestions.Models.ModuleGroupCollection
<div>
@Model.Name
</div>
<div>
@Model.HtmlDivId
</div>