灵活掌握Asp.net MVC中GridView的使用方法
程序员文章站
2023-11-22 10:52:34
本文教程为大家分享了gridview控件的使用方法和具体实现代码,供大家参考,具体内容如下
models文件下实体类:
public class custom...
本文教程为大家分享了gridview控件的使用方法和具体实现代码,供大家参考,具体内容如下
models文件下实体类:
public class customer { public int id { get; set; } public string companyname { get; set; } public string contacttitle { get; set; } public string address { get; set; } public string city { get; set; } public string country { get; set; } public string phone { get; set; } public datetime founded { get; set; } }
public class customersviewmodel { public iqueryable<customer> customers { get; set; } public paginginfo paginginfo { get; set; } public string jsonpaginginfo { get; set; } }
public static class expresssionbuilder { private static readonly methodinfo containsmethod = typeof(string).getmethod("contains"); private static readonly methodinfo startswithmethod = typeof(string).getmethod("startswith", new type[] { typeof(string) }); private static readonly methodinfo endswithmethod = typeof(string).getmethod("endswith", new type[] { typeof(string) }); public static expression<func<t,bool>> getexpression<t>(ilist<filterobject> filters) { if (filters.count == 0) return null; parameterexpression param = expression.parameter(typeof(t), "t"); expression exp = null; if (filters.count == 1) exp = getexpression<t>(param, filters[0]); else if (filters.count == 2) exp = getexpression<t>(param, filters[0], filters[1]); else { while (filters.count > 0) { var f1 = filters[0]; var f2 = filters[1]; if (exp == null) exp = getexpression<t>(param, filters[0], filters[1]); else exp = expression.andalso(exp, getexpression<t>(param, filters[0], filters[1])); filters.remove(f1); filters.remove(f2); if (filters.count == 1) { exp = expression.andalso(exp, getexpression<t>(param, filters[0])); filters.removeat(0); } } } return expression.lambda<func<t, bool>>(exp, param); } private static expression getexpression<t>(parameterexpression param, filterobject filter) { memberexpression member = expression.property(param, filter.column); //constantexpression constant = expression.constant(filter.value); //新的逻辑来处理可空decimal和datetime值 unaryexpression constant = null; if (member.type == typeof(decimal?)) { constant = expression.convert(expression.constant(decimal.parse(filter.value)) , member.type); } else if (member.type == typeof(datetime?)) { constant = expression.convert(expression.constant(datetime.parse(filter.value)), member.type); } else { constant = expression.convert(expression.constant(filter.value), member.type); } switch (filter.operator) { case filteroperator.equals: return expression.equal(member, constant); case filteroperator.greaterthan: return expression.greaterthan(member, constant); case filteroperator.greaterthanorequal: return expression.greaterthanorequal(member, constant); case filteroperator.lessthan: return expression.lessthan(member, constant); case filteroperator.lessthanorequal: return expression.lessthanorequal(member, constant); case filteroperator.contains: return expression.call(member, containsmethod, constant); case filteroperator.startswith: return expression.call(member, startswithmethod, constant); case filteroperator.endswith: return expression.call(member, endswithmethod, constant); case filteroperator.notequal: return expression.negate(expression.equal(member, constant)); } return null; } private static binaryexpression getexpression<t> (parameterexpression param, filterobject filter1, filterobject filter2) { expression bin1 = getexpression<t>(param, filter1); expression bin2 = getexpression<t>(param, filter2); return expression.andalso(bin1, bin2); } }
public class paginginfo { public list<int> pageoptions { get; set; } public bool showpageoptions { get; set; } public int totalitems { get; set; } public int itemsperpage { get; set; } public int currentpage { get; set; } public int totalpages { get { return (int)math.ceiling((decimal)totalitems / (itemsperpage != 0 ? itemsperpage : 1)); } } public sortobject sort { get; set; } public ilist<filterobject> filters { get; set; } public string searchterm { get; set; } } public class sortobject { public string sortcolumn { get; set; } public sortdirection direction { get; set; } } public class filterobject { public string column { get; set; } public string value { get; set; } public filteroperator operator { get; set; } public filterconjunction conjunction { get; set; } } /********* enums *************/ public enum sortdirection { notset, ascending, descending } public enum filteroperator { contains, greaterthan, greaterthanorequal, lessthan, lessthanorequal, startswith, endswith, equals, notequal } public enum filterconjunction { and, or } public class extensions { public static string getwhereclause(filterobject filterobj, type valuetype) { string whereclause = "true"; if (valuetype != typeof (datetime)) { switch (filterobj.operator) { case filteroperator.contains: if (valuetype == typeof (string)) whereclause += string.format(" {0} {1}.contains(\"{2}\")", filterobj.conjunction, filterobj.column, filterobj.value); break; case filteroperator.greaterthan: if (valuetype != typeof (string)) whereclause += string.format(" {0} {1} > {2}", filterobj.conjunction, filterobj.column, filterobj.value); break; case filteroperator.greaterthanorequal: if (valuetype != typeof (string)) whereclause += string.format(" {0} {1} >= {2}", filterobj.conjunction, filterobj.column, filterobj.value); break; case filteroperator.lessthan: if (valuetype != typeof (string)) whereclause += string.format(" {0} {1} < {2}", filterobj.conjunction, filterobj.column, filterobj.value); break; case filteroperator.lessthanorequal: if (valuetype != typeof (string)) whereclause += string.format(" {0} {1} <= {2}", filterobj.conjunction, filterobj.column, filterobj.value); break; case filteroperator.startswith: if (valuetype != typeof (string)) whereclause += string.format(" {0} {1}.startswith(\"{2}\")", filterobj.conjunction, filterobj.column, filterobj.value); break; case filteroperator.endswith: if (valuetype != typeof (string)) whereclause += string.format(" {0} {1}.endswith(\"{2}\")", filterobj.conjunction, filterobj.column, filterobj.value); break; case filteroperator.equals: whereclause += string.format(valuetype == typeof (string) ? " {0} {1} == \"{2}\"" : " {0} {1} == {2}", filterobj.conjunction, filterobj.column, filterobj.value); break; case filteroperator.notequal: whereclause += string.format(valuetype == typeof (string) ? " {0} {1} != \"{2}\"" : " {0} {1} != {2}", filterobj.conjunction, filterobj.column, filterobj.value); break; default: throw new argumentoutofrangeexception(); } } else { datetime dt; datetime.tryparse(filterobj.value, out dt); switch (filterobj.operator) { case filteroperator.contains: break; case filteroperator.greaterthan: whereclause += string.format(" {0} {1} > datetime(\"{2}\")", filterobj.conjunction, filterobj.column, dt); break; case filteroperator.greaterthanorequal: whereclause += string.format(" {0} {1} >= datetime(\"{2}\")", filterobj.conjunction, filterobj.column, dt); break; case filteroperator.lessthan: whereclause += string.format(" {0} {1} < datetime(\"{2}\")", filterobj.conjunction, filterobj.column, dt); break; case filteroperator.lessthanorequal: whereclause += string.format(" {0} {1} <= datetime(\"{2}\")", filterobj.conjunction, filterobj.column, dt); break; case filteroperator.startswith: break; case filteroperator.endswith: break; case filteroperator.equals: whereclause += string.format(" {0} {1} == datetime(\"{2}\")", filterobj.conjunction, filterobj.column, dt); break; case filteroperator.notequal: whereclause += string.format(" {0} {1} != datetime(\"{2}\")", filterobj.conjunction, filterobj.column, dt); break; default: throw new argumentoutofrangeexception(); } } return whereclause; } }
public class gridviewmodelprovider { internal static customersviewmodel getcustomersviewmodel(mydbcontext db, paginginfo pagingdata) { int totalitems = 0; var model = new customersviewmodel() { customers = getresources(db.customers.asqueryable(), pagingdata, out totalitems), paginginfo = new paginginfo() { currentpage = pagingdata.currentpage, itemsperpage = pagingdata.itemsperpage, pageoptions = new list<int>() { 10, 25, 50, 100 }, showpageoptions = true, searchterm = pagingdata.searchterm, sort = pagingdata.sort, filters = pagingdata.filters } }; model.paginginfo.totalitems = totalitems; model.jsonpaginginfo = json.encode(model.paginginfo); return model; } private static iqueryable<customer> getresources(iqueryable<customer> customers, paginginfo pagingdata, out int totalitems) { var customers = customers; //search if (!string.isnullorempty(pagingdata.searchterm)) { customers = customers.where(x => (x.companyname.contains(pagingdata.searchterm) || x.contacttitle.contains(pagingdata.searchterm))); } //filter if (pagingdata.filters != null) { foreach (var filterobj in pagingdata.filters) { switch (filterobj.column) { case "city": if (filterobj.value.tolower() != "all") customers = customers.where(extensions.getwhereclause(filterobj, typeof(string))); break; //add other filter columns here } } } totalitems = customers.count(); //sort customers = customers.orderby(x => x.id); if (pagingdata.sort != null) { switch (pagingdata.sort.direction) { case sortdirection.ascending: if (pagingdata.sort.sortcolumn == "companyname") { customers = customers.orderby(x => x.companyname); } else if (pagingdata.sort.sortcolumn == "contacttitle") { customers = customers.orderby(x => x.contacttitle); } break; case sortdirection.descending: if (pagingdata.sort.sortcolumn == "companyname") { customers = customers.orderbydescending(x => x.companyname); } else if (pagingdata.sort.sortcolumn == "contacttitle") { customers = customers.orderbydescending(x => x.contacttitle); } break; case sortdirection.notset: default: break; } } customers = customers .skip((pagingdata.currentpage - 1) * pagingdata.itemsperpage).take(pagingdata.itemsperpage); return customers; } }
/// <summary> /// 启用查询谓词的高效,动态组合。 /// </summary> public static class predicatebuilder { /// <summary> /// 创建一个计算结果为true的谓词。 /// </summary> public static expression<func<t, bool>> true<t>() { return param => true; } /// <summary> /// 创建一个计算结果为false的谓词 /// </summary> public static expression<func<t, bool>> false<t>() { return param => false; } /// <summary> /// 创建一个从指定的lambda表达式的谓词表达式。 /// </summary> public static expression<func<t, bool>> create<t>(expression<func<t, bool>> predicate) { return predicate; } /// <summary> /// 结合了第二第一谓词使用逻辑“and”。 /// </summary> public static expression<func<t, bool>> and<t>(this expression<func<t, bool>> first, expression<func<t, bool>> second) { return first.compose(second, expression.andalso); } /// <summary> /// 结合了第二第一谓词使用逻辑“or”。 /// </summary> public static expression<func<t, bool>> or<t>(this expression<func<t, bool>> first, expression<func<t, bool>> second) { return first.compose(second, expression.orelse); } /// <summary> ///否定谓词 /// </summary> public static expression<func<t, bool>> not<t>(this expression<func<t, bool>> expression) { var negated = expression.not(expression.body); return expression.lambda<func<t, bool>>(negated, expression.parameters); } /// <summary> /// 使用指定的合并函数,合并第二和第一表达式 /// </summary> static expression<t> compose<t>(this expression<t> first, expression<t> second, func<expression, expression, expression> merge) { //第二参数映射到第一参数 var map = first.parameters .select((f, i) => new { f, s = second.parameters[i] }) .todictionary(p => p.s, p => p.f); //第一lambda表达式的参数替换在第二lambda表达式参数 var secondbody = parameterrebinder.replaceparameters(map, second.body); //从第一个表达式创建一个带参数的合并lambda表达式 return expression.lambda<t>(merge(first.body, secondbody), first.parameters); } class parameterrebinder : expressionvisitor { readonly dictionary<parameterexpression, parameterexpression> map; parameterrebinder(dictionary<parameterexpression, parameterexpression> map) { this.map = map ?? new dictionary<parameterexpression, parameterexpression>(); } public static expression replaceparameters(dictionary<parameterexpression, parameterexpression> map, expression exp) { return new parameterrebinder(map).visit(exp); } protected override expression visitparameter(parameterexpression p) { parameterexpression replacement; if (map.trygetvalue(p, out replacement)) { p = replacement; } return base.visitparameter(p); } } }
mydbcontext.cs代码:
public class mydbcontext : dbcontext { public mydbcontext() : base("defaultconnection") { } public dbset<customer> customers { get; set; } protected override void onmodelcreating(dbmodelbuilder modelbuilder) { modelbuilder.entity<customer>().property(c => c.companyname).hasmaxlength(40); modelbuilder.entity<customer>().property(c => c.contacttitle).hasmaxlength(40); } }
homecontroller.cs控制器:
public class homecontroller : controller { public actionresult index() { var model = new customersviewmodel() { customers = null, paginginfo = new paginginfo() { currentpage=1, itemsperpage= 10, pageoptions = new list<int>() { 10,25, 50, 100}, showpageoptions= true, totalitems=1 } }; return view(model); } public actionresult getcustomers(paginginfo pagingdata) { var db = new mydbcontext(); var model = gridviewmodelprovider.getcustomersviewmodel(db, pagingdata); return partialview("_customerspartial", model); } public actionresult about() { viewbag.message = "您的应用程序描述页面。"; return view(); } public actionresult contact() { viewbag.message = "您的联系页面。"; return view(); } }
home视图文件夹下:
_customerspartial.cshtml
@model mesoft.gridview.models.customersviewmodel @*在这里写下返回的数据的详细信息*@ <span class="gridview-data-details" style="display:none;">@html.raw(model.jsonpaginginfo)</span> <table class="table table-bordered table-striped"> <thead> <tr class="gridview-list-header"> <th> @(html.displaynamefor(x => x.customers.firstordefault().id)) </th> <th class="sortable" data-sort="companyname"> @(html.displaynamefor(x => x.customers.firstordefault().companyname)) </th> <th class="sortable" data-sort="contacttitle"> @(html.displaynamefor(x => x.customers.firstordefault().contacttitle)) </th> <th> @(html.displaynamefor(x => x.customers.firstordefault().country)) </th> <th> @(html.displaynamefor(x => x.customers.firstordefault().city)) </th> <th> @(html.displaynamefor(x => x.customers.firstordefault().address)) </th> <th> @(html.displaynamefor(x => x.customers.firstordefault().phone)) </th> <th> @html.displaynamefor(x=> x.customers.firstordefault().founded) </th> </tr> </thead> <tbody id="customerstable" class="gridview-list-items"> @if (model.customers.any()) { foreach (var c in model.customers) { <tr> <td class="value">@c.id</td> <td class="value">@c.companyname</td> <td class="value">@c.contacttitle</td> <td class="value">@c.country</td> <td class="value">@c.city</td> <td class="description">@c.address</td> <td class="value">@c.phone</td> <td>@c.founded</td> </tr> } } else { <tr> <td colspan="8"> <div class="alert alert-warning alert-dismissable"> <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button> <strong>警告!</strong> 没有客户找到! </div> </td> </tr> } @html.raw(viewbag.script) </tbody> </table>
_gridviewpartial.cshtml
@model mesoft.gridview.models.customersviewmodel <!-- gridview--> <div class="gridview gridview1"> <!-- gridview header--> <div class="gridview-header"> <!--gridview的头的左边部分--> <div class="col-sm-6"> <div class="gridview-search"> <div class="search input-group"> <input class="form-control" placeholder="search" type="search"> <span class="input-group-btn"> <button class="btn btn-default" type="button"> <span class="fa fa-search"></span> <span class="sr-only">search</span> </button> </span> </div> </div> </div> <!-- gridview的头右边部分--> <div class="col-sm-6 text-right"> <!-- 这里添加任何筛选操作--> @{ string[] cityfilters = {"istanbul", "trabzon", "ankara", "izmir", "samsun", "erzurum"}; } 根据城市筛选: <div class="btn-group"> <button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown"> select city <span class="caret"></span> </button> <ul class="dropdown-menu filter-parent" role="menu"> @foreach (var city in cityfilters) { <li><a href="#" class="filter" data-filter-column="city" data-filter-value="@city" data-filter-operator="@mesoft.gridview.models.filteroperator.equals" data-filter-conjunction="@mesoft.gridview.models.filterconjunction.and">@city</a></li> } <li class="divider"></li> <li class="active"><a href="#" class="filter" data-filter-column="city" data-filter-value="all">all</a></li> </ul> </div> </div> </div> <!-- gridview viewport--> <div class="gridview-viewport" id="viewport" data-getdata-function="@url.action("getcustomers", "home")" data-default-pagesize="10"> <div class="gridview-canvas" style="min-height:400px;"> @*data will load here*@ </div> <div class="loading gridview gridview-loader"> <img src="~/content/images/loading.gif" /> </div> </div> <!-- gridview的分页区域--> <div class="gridview-footer"> @html.displayfor(x => x.paginginfo, "pager") </div> </div>
about.cshtml
@{ viewbag.title = "about"; } <h2>@viewbag.title.</h2> <h3>@viewbag.message</h3> <p>#</p>
contact.cshtml
@{ viewbag.title = "contact"; } <h2>@viewbag.title.</h2> <h3>@viewbag.message</h3> <address> <strong>support:</strong> <a href="827937686@qq.com">827937686@qq.com</a><br /> </address>
index.cshtml
@model mesoft.gridview.models.customersviewmodel @{ viewbag.title = "home page"; } <div class="jumbotron"> <h1>gridview</h1> <p class="lead">简单易用,开发简单</p> <p><a href="#" class="btn btn-primary btn-lg">learn more »</a></p> </div> <!-- gridview area--> <div class="row"> @html.partial("_gridviewpartial") </div> @section scripts { <script> $('.gridview1').megridview(); //$('.gridview2').megridview(); </script> }
shared文件夹下:
_layout.cshtml
<!doctype html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>@viewbag.title -gridview的用法示例应用程序</title> @styles.render("~/content/css") @scripts.render("~/bundles/modernizr") </head> <body> <div class="navbar navbar-inverse navbar-fixed-top"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> @html.actionlink("gridview", "index", "home", new { area = "" }, new { @class = "navbar-brand" }) </div> <div class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li>@html.actionlink("home", "index", "home")</li> <li>@html.actionlink("about", "about", "home")</li> <li>@html.actionlink("contact", "contact", "home")</li> </ul> @*@html.partial("_loginpartial")*@ </div> </div> </div> <div class="container body-content"> @renderbody() <hr /> <footer> <p>© @datetime.now.year - wulex</p> </footer> </div> @scripts.render("~/bundles/jquery") @scripts.render("~/bundles/bootstrap") @rendersection("scripts", required: false) </body> </html>
运行结果如图:
为大家附3个精彩的专题:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
上一篇: javaScript语法总结