ASP.NET MVC 学习笔记(三),排序加查找
首先先说排序
非常的简单
代码如下
//创建视图 public ViewResult Index() { //升序排列 IEnumerable<Product> Prodcuts = repository.Products.OrderBy(x => x.Price); //下面的是降序排列 repository.Products.OrderByDescending(x => x.Price); List<Product> p = Prodcuts.ToList(); QuickSort(0, p.Count - 1, p); string s1 = "123"; //List<Product> list= Prodcuts.AsQueryable().OrderBy(x => x.Price).ToList(); // foreach (var item in Prodcuts) // { // string p = item.Category; // } Prodcuts = p; return View(Prodcuts); }
核心语句 orderBy 升序,降序 OrderByDescending
查找数据
1 创建查找的动作方法
[HttpPost] public ActionResult Query(string Name) { IEnumerable<Product> p = repository.Products.Where(x => x.Category== Name||x.ProductName.Contains(Name)); if (p != null) { return View("QueryResult", p); } else { return View("QueryResult",p); } }
没什么的可解释的,
Html 代码
@using Domain.Entities @model IEnumerable<Product> @{ ViewBag.Title = "Index"; } <h2>Index</h2> @* 查询再这里 *@ @using (Html.BeginForm("Query","Product")) { @Html.TextBox("Name"); <input type="submit" value="查询" /> } <table class="table table-bordered table-striped table-condensed" > <tr> <th class="text-center">id</th> <th class="text-center">产品名</th> <th class="text-center">描述</th> <th class="text-center">种类</th> <th class="text-center">价格</th> <th class="text-center">删除</th> </tr> @foreach (var item in Model) { <tr> <td>@item.ProductID</td> <td>@Html.ActionLink(item.ProductName, "Edit", new { item.ProductID })</td> <td>@item.Description</td> <td>@item.Category</td> <td>@item.Price.ToString()</td> <td> @using (Html.BeginForm("Delete", "Product")) { @Html.Hidden("ProductId", item.ProductID) <input class="btn btn-danger" type="submit" value="删除"/> } </td> </tr> } </table> <div class="panel-footer"> @Html.ActionLink("添加", "Create", new { @class="btn btn-default"}) </div>
查询结构视图没什么好解释的就一个Foreach
@using Domain.Entities @model IEnumerable<Product> @{ ViewBag.Title = "QueryResult"; } <h2>QueryResult</h2> <table border="1"> @if (Model.Count()>0) { foreach (var item in Model) { <tr> <td>@item.ProductName</td> <td>@item.Description</td> <td>@item.Category</td> <td>@item.Price</td> </tr> } } else { <tr> <td>没有查询到</td> </tr> } </table>
测试结果