[英]How to order data column by number in MVC?
我是MVC的新手,我想按数字排序结果数据
1-
2
3
....
在控制器中
public ActionResult Index()
{
var all = from emp in db.Details select emp;
return View( all);
}
在我看来
<table class="table table-bordered">
<tr>
<th class="th">Id</th>
<th class="th">Name</th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>@Html.DisplayFor(x => item.Id)</td>
<td>@Html.DisplayFor(x => item.Name)</td>
<td>@Html.ActionLink("Edit", "Edit", new { id = item.Id })</td>
</tr>
}
</table>
我想查看页面中的结果是按编号1- 2- 3- .....排序
您使用orderby
关键字进行排序。 例如:
var all = from emp in db.Details orderby emp.SomeField select emp;
只需使用emp
对象上具有您要排序的值的任何字段即可。
编辑:基于以下注释,听起来您似乎只想显示一个递增的整数(类似于ol
,但在table
)。 这听起来更像是对视图本身的责任,也许像这样带有一个简单的for
循环:
@for(var i = 0; i < Model.Count(); i++)
{
<tr>
<td>@i</td>
<td>@Html.DisplayFor(x => Model[i].Id)</td>
<td>@Html.DisplayFor(x => Model[i].Name)</td>
<td>@Html.ActionLink("Edit", "Edit", new { id = Model[i].Id })</td>
</tr>
}
您可能需要将模型的类型从IEnumerable<T>
更改为IList<T>
以便对其进行索引。 可能还会在将其发送到视图之前,在控制器中的模型上调用.ToList()
。
(在进行枚举时要小心,因为当只需要一个集合的一部分时,它可能导致不必要地实现整个集合。但是在这种情况下,无论如何,整个集合都是由视图引擎实现的,因此不应有太大的不同)
将您的foreach更改为for并使用迭代器
<table class="table table-bordered">
<tr>
<th> class="th">number</th>
<th class="th">Id</th>
<th class="th">Name</th>
<th>Some other column so your table renders correctly</th>
</tr>
@for(int i = 0; i < Model.Count; i++)
{
<tr>
<td>@i.ToString()<!-- i put the number here but whateves. --></td>
<td>@Html.DisplayFor(x => Model[i].Id)</td>
<td>@Html.DisplayFor(x => Model[i].Name)</td>
<td>@Html.ActionLink("Edit", "Edit", new { id = item.Id })</td>
</tr>
}
</table>
static void Main(string[] args)
{
List<TestClass> a = new List<TestClass>();
TestClass t1 = new TestClass();
t1.Test1 = "a";
t1.Test2 = "b";
t1.Test3 = "c";
t1.Test4 = "d";
TestClass t2 = new TestClass();
t2.Test1 = "a2";
t2.Test2 = "b3";
t2.Test3 = "c4";
t2.Test4 = "d5";
a.Add(t1);
a.Add(t2);
var result = (from collRow in a
select collRow).Select((d, i) => new
{
Data = d,
Index = i
});
foreach(var p in result)
{
Console.WriteLine(p.Index);
}
Console.ReadKey();
}
这是在linq中实现的一种方法,您应该使用Select来为您传递索引。 这里的MSDN文章关于它更多的例子: 文章
所以在代码中应该像这样。
//probably it will be needed to be add .AsEnumerable() before the Select
var all = (from emp in db.Details select emp).Select((d, i) => new
{
Data = d,
// if you want the index to start from 1, Index=i+1
Index = i
});
之后,您认为:
@foreach (var item in Model)
{
<tr>
<td>@Html.DisplayFor(x => item.Index)</td>
<td>@Html.DisplayFor(x => item.Data.ID)</td>
<td>@Html.DisplayFor(x => item.Data.Name)</td>
<td>@Html.ActionLink("Edit", "Edit", new { id = item.Data.ID })</td>
</tr>
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.