我正在创建一个MVC3 Web应用程序。我有一个表填充了我的数据库中的数据但是想知道如何让它只显示我的概要的前三行而不是全部10行。我认为这有与HTML Helpers有关但是想知道你是否有人能帮我找到合适的代码????? 任何帮助都会很棒!
@model IEnumerable<TheatreGroup.Models.Show>
@{
ViewBag.Title = "Shows";
}
<h2>
Shows</h2>
<p>Below is a list of shows which will be avalible in the next couple of weeks</p>
<p>
@Html.ActionLink("Create New", "Create")
</p>
@using (Html.BeginForm())
{
<p>
Find by name: @Html.TextBox("SearchString")
<input type="submit" value="Search" /></p>
}
<table>
<tr>
<th>
@Html.ActionLink("name", "Index", new { sortOrder = ViewBag.nameSortParm,})
</th>
<th>
@Html.ActionLink("writer", "Index", new { sortOrder = ViewBag.writerSortParm,})
</th>
<th>
@Html.ActionLink("synopsis", "Index", new { sortOrder = ViewBag.synopsisSortParm, })
</th>
<th>
</th>
</tr>
@foreach (var item in Model){
<tr>
<td>
@Html.DisplayFor(modelItem => item.name)
</td>
<td>
@Html.DisplayFor(modelItem => item.writer)
</td>
<td>
@Html.DisplayFor(modelItem => item.synopsis)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id = item.showid }) |
@Html.ActionLink("Details", "Details", new { id = item.showid }) |
@Html.ActionLink("Delete", "Delete", new { id = item.showid })
</td>
</tr>
}
</table>
答案 0 :(得分:3)
我将我的答案分为两种状态:
您需要在页面流程的更下方的其他7行(如“显示更多结果”链接)
您不需要列表的其余部分。
解决方案1:
使用@Dangerous说的话。
@for (int i=0; i<3; i++)
{
@Html.DisplayFor(m => m[i].name) // And the rest of the data
}
请注意如果您没有3个元素,则此代码将引发异常。 您可以做的是检查计数是否小于3,然后运行到该数字。
你可能还想在foreach循环上运行,只是给某些类隐藏它的类{@class ='hidden'}然后当你按某条线时,只需使用Javascript(jQuery)即可告诉他们。
解决方案2:
如果您不需要其余元素,则在将模型发送到视图时,只需使用take。
public ActionResult Action()
{
var model = GetListFromDatabase().Take(3); // LINQ
return View(model);
}
您可能需要ToList()才能使其正常工作,具体取决于
通过这种方式,您可以保持代码不变,只需缩短发送到View的元素数量。
希望它有所帮助!
答案 1 :(得分:0)
您正在使用@foreach (var item in Model)
来显示每一行。
尝试使用@for (int i=0; i<3; i++)
,以便循环显示前3项。
然后,您需要将模型引用为显示器的@Html.DisplayFor(m => m[i].name)
等。我相信这应该有用。