我有一个名为ViewModel的MyViewModel,它包含:
public IList<Config> Config { get; set; }
public bool Disabled { get; set; }
public string Name { get; set; }Config是一个包含ID & Value的对象。
在Controller方面,我正在填充所有的值,在视图中,我需要访问这个Config单个项的列表,其中id = x和它应该在label中显示相应的值。为此,我需要一个强类型的标签,大致如下所示:
@Html.LabelFor(a => ....)我不确定我的Linq语句应该是什么来在label Config.Id = x中显示Config.Id = x。任何帮助都将不胜感激。谢谢
发布于 2014-12-02 21:52:43
若要显示按ID值分组的表,请首先创建所有现有Id编号的列表。
ViewBag.Ids = Config.Select(x => x.Id).Distinct(); //create list of all existing Ids通过ViewBag将该列表传递到您的视图中,并遍历它以及对象列表:
@foreach(int IdNum in ViewBag.Ids)
{
<table>
@foreach(Config c in Config.Where(x=> x.Id == IdNum))
{
<tr>
<td> @c.ID </td>
<td> @c.property1 </td>
<td> @c.property2 </td>
</tr>
}
</table>
}在这种情况下,我不会费心使用LabelFor()方法,因为只使用@object.property与HTML内联就足够容易了。
发布于 2014-12-02 22:32:30
若要按组显示列表,请尝试如下
<table>
@{
foreach (var group in Model.Config.GroupBy(x => x.Id))
{
<tr>
<td>@group.Key</td> </tr>
int index =0;
@foreach(Config c in Model.Config.Where(x=> x.Id == group.Key))
{
<tr>
<td> @Model.Config[index].ID </td>
<td> @Model.Config[index].property1 </td>
<td> @Model.Config[index].property2 </td>
</tr>
index++;
}
}
}
</table>发布于 2014-12-03 12:31:07
睡过几次觉后,我终于得到了它。这就是我要找的:
@Html.Label(Model.Config.FirstOrDefault(x => x.ConfigId == "x").Value)但是,由于某些原因,它不能在@Html.Display上工作。知道为什么吗?谢谢大家的意见和建议。
https://stackoverflow.com/questions/27259612
复制相似问题