标签:匿名 匿名对象 lis HERE inf 对象 jquery image ==
使用数据库:NorthWind示例数据库 (链接:https://www.cnblogs.com/liverpool/p/4718042.html)
后台代码:
namespace T1_EF.Controllers { public class CustomersController : Controller { // GET: Customers public ActionResult Index() { //NorthwindEntities northwind = new NorthwindEntities(); //var list = northwind.Customers.Select(c =>c); //建议使用下面这种写法,面向抽象编程,使用多态,并且更灵活 //DbContext dbContext = new NorthwindEntities(); //var list = dbContext.Set<Customers>().Select(c => c); //使用Linq练习操作 dynamic list; DbContext db = new NorthwindEntities(); //基本查询 //list = from customer in db.Set<Customers>() select customer; //单条件查询 //list = from customer in db.Set<Customers>() where customer.Country == "USA" select customer; //多条件查询 //list = from customer in db.Set<Customers>() // where customer.Country == "USA" || customer.Country == "Canada" // select customer; //查询单列(这样就不能使用强类型视图了) //list = from customer in db.Set<Customers>() select customer.Country; //查询多列(将select后换为匿名对象或者要展示的对象)(建议新增viewModel作为视图对象,否则在前台数据必须进行反序列化操作) //list = from customer in db.Set<Customers>() select new CustomerModel{ ContactName= customer.ContactName,CompanyName= customer.CompanyName }; //分页,Skip就是跳过元素,Take就是要返回排在前面的几个元素,一般与OrderBy排序使用(注意:是方法特有的,不是Linq写法) list = (from customer in db.Set<Customers>() select customer).OrderBy(c => c.CompanyName).Skip(5).Take(15); ViewData.Model = list; return View(); } public ActionResult FuncTionIndex() { //使用方法进行查询 DbContext db = new NorthwindEntities(); //返回全部数据 var list = db.Set<Customers>(); //单条件查询(像JQuery的树一样叠加) //var list1 = list.Where(c => c.Country == "USA"); //多条件 //var list1 = list.Where(c => c.Country == "USA" || c.Country == "Canada"); //单列或者多列查询 //var list1 = list.Select(c => //new CustomerModel { CompanyName = c.CompanyName, ContactName = c.ContactName }); ViewData.Model = list1; return View(); } } }
前台代码:
@model IEnumerable<T1_EF.Models.Customers> @*@model IEnumerable<T1_EF.ViewModels.CustomerModel>*@ @{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>FuncTionIndex</title> </head> <body> <div> <table border="1"> <tr> <td>联系人姓名</td> <td>客户公司</td> <td>客户属国</td> </tr> @foreach (var item in Model) { <tr> <td>@item.ContactName</td> <td>@item.CompanyName</td> <td>@item.Country</td> </tr> } </table> </div> </body> </html>
显示效果:
End
标签:匿名 匿名对象 lis HERE inf 对象 jquery image ==
原文地址:https://www.cnblogs.com/LeeSki/p/12261837.html