C# 为数据库中的信息添加编号
我正在使用ASP>NETMVC,从数据库中提取信息并将其显示在视图页面上。它工作得很好,但是有没有办法在开始时添加索引号 例如,目前显示如下: 姓名年龄性别 安妮24女 亚伦17男 我希望做到: 索引名年龄性别 1安妮24女 2亚伦17男 我可以从数据库中提取ID,但它们不一定是正确的增量值。我尝试通过ViewBag增加,但没有成功。考虑到增量发生在列表之外,预计为。。在控制器和视图中,我的代码如下所示C# 为数据库中的信息添加编号,c#,html,asp.net-mvc,razor,C#,Html,Asp.net Mvc,Razor,我正在使用ASP>NETMVC,从数据库中提取信息并将其显示在视图页面上。它工作得很好,但是有没有办法在开始时添加索引号 例如,目前显示如下: 姓名年龄性别 安妮24女 亚伦17男 我希望做到: 索引名年龄性别 1安妮24女 2亚伦17男 我可以从数据库中提取ID,但它们不一定是正确的增量值。我尝试通过ViewBag增加,但没有成功。考虑到增量发生在列表之外,预计为。。在控制器和视图中,我的代码如下所示 //Controller public ActionResult Index() {
//Controller
public ActionResult Index()
{
int count = 1;
ViewBag.Count = count++;
return View(db.Person.ToList());
}
//View
<table class="table">
<tr>
<th>
Index
</th>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.Age)
</th>
<th>
@Html.DisplayNameFor(model => model.Gender)
</th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@ViewBag.Count
</td>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Age)
</td>
<td>
@Html.DisplayFor(modelItem => item.Gender)
</td>
</tr>
}
</table>
//控制器
公共行动结果索引()
{
整数计数=1;
ViewBag.Count=Count++;
返回视图(db.Person.ToList());
}
//看法
指数
@DisplayNameFor(model=>model.Name)
@DisplayNameFor(model=>model.Age)
@DisplayNameFor(model=>model.Gender)
@foreach(模型中的var项目){
@查看包。计数
@DisplayFor(modelItem=>item.Name)
@DisplayFor(modelItem=>item.Age)
@DisplayFor(modeleItem=>item.Gender)
}
在razor中使用“for loop”,类似于:
@for(var i = 10; i < 21; i++)
{<p>Line @i</p>}
(变量i=10;i<21;i++)
{Line@i}
在视图中声明计数器(不需要
ViewBag
属性),并在循环中递增计数器
@{ int counter = 1; }
<table class="table">
<tr>
<th>Index</th>
<th>@Html.DisplayNameFor(model => model.Name)</th>
....
</tr>
@foreach (var item in Model) {
<tr>
<td>@counter</td>
<td>@Html.DisplayFor(modelItem => item.Name)</td>
....
</tr>
counter++;
}
</table>
@{int counter=1;}
指数
@DisplayNameFor(model=>model.Name)
....
@foreach(模型中的var项目){
@柜台
@DisplayFor(modelItem=>item.Name)
....
计数器++;
}
您的意思是只想让它出现在视图中吗?如果是这样,请添加@{int count=1;}
和一个表列-@count
,并在foreach
循环中递增。@StephenMuecke在指出这个问题后问这个问题会觉得很愚蠢。。谢谢