要在ASP.NET MVC视图中动态创建表结构,可以使用循环和嵌套对象来遍历ViewModel集合,并根据对象的属性动态生成表格。
以下是一个示例解决方案:
public class ParentViewModel
{
public string ParentName { get; set; }
public List Children { get; set; }
}
public class ChildViewModel
{
public string ChildName { get; set; }
public int ChildAge { get; set; }
}
public ActionResult Index()
{
var parentViewModel = new ParentViewModel
{
ParentName = "Parent",
Children = new List
{
new ChildViewModel { ChildName = "Child 1", ChildAge = 10 },
new ChildViewModel { ChildName = "Child 2", ChildAge = 12 },
new ChildViewModel { ChildName = "Child 3", ChildAge = 8 }
}
};
return View(parentViewModel);
}
@model ParentViewModel
Parent Name
Child Name
Child Age
@Model.ParentName
@Model.Children[0].ChildName
@Model.Children[0].ChildAge
@foreach (var child in Model.Children.Skip(1))
{
@child.ChildName
@child.ChildAge
}
在这个示例中,我们首先在表头中创建了三个列的标题。然后,在第一个tr中,我们展示了ParentViewModel对象的属性值。接下来,使用foreach循环遍历剩余的ChildViewModel对象,并在表格中创建子对象的行。
这样,就可以动态地创建表结构,并显示嵌套对象的属性值。