我是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- ..... 感谢
答案 0 :(得分:1)
您使用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()
。
(在枚举时要小心,因为当只需要一部分时,它可能导致整个集合的不必要的实现。但是在这种情况下,整个集合无论如何都由视图引擎实现,所以它不应该&#39; t产生重大影响。)
答案 1 :(得分:0)
将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>
答案 2 :(得分:0)
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文章,附有更多例子:Article
所以在代码中应该喜欢这样的东西。
//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>
}