This tutorial for you to share the GridView control of the use and specific implementation code, for your reference, the specific contents are as follows
Entity classes under Models files:
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);
New logic to handle nullable decimal and datetime values 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));
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 Filte Roperator {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 (Valuetyp E = = 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, Pagingi
NFO pagingdata) {int totalitems = 0; var model = new Customersviewmodel () {Customers = getresources (db. Customers.asqueryable (), PagingData, out totalitems), Paginginfo = new Paginginfo () {currentpage = Pagingdata.cu Rrentpage, ItemsPerPage = pagingdata.itemsperpage, pageoptions = new list<int> () {Ten, M, MB}, SHOWP
Ageoptions = 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 (filte Robj.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.
By (x => x.id); if (pagingdata.sort!= null) {switch (PagingData.Sort.Direction) {case SortDirection.Ascending:if (Pagingda Ta. Sort.sortcolumn = = "CompanyName") {customers = customers.
By (x => x.companyname); else if (PagingData.Sort.SortColumn = = "ContactTitle") {customers = customers.
By (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>///enables efficient, dynamic combination of query predicates.
</summary> public static class Predicatebuilder {///<summary>///creates a predicate that evaluates to true.
</summary> public static expression<func<t, bool>> true<t> () {return param => True;} <summary>///Create a predicate that evaluates to false///</summary> public static expression<func<t, bool>> Fals
E<t> () {return param => false;}
<summary>///creates a predicate expression from the specified lambda expression. </summary> public static expression<func<t, bool>> create<t> (Expression<func<t,
Bool>> predicate) {return predicate;}
<summary>///combines the second first predicate with the logical "and". </summary> public static expression<func<t, bool>> and<t> (This expression<func<t,
Bool>>, Expression<func<t, bool>> second) {return first.compose (second, expression.andalso);
///<summary>///combines the second first predicate with the logical "or". </summary> public static expression<func<t, bool>> or<t> (this expression<func<t, bool>>
Expression<func<t, bool>> second) {return first.compose (second, expression.orelse); }///<summary>///negative predicate///</summary> public static expression<func<t, bool>> not<t> (T His expression<func<t, bool>> Expression) {var negated = Expression.not (Expression.
body); Return expression.lambda<func<t, bool>> (negated, Expression.
Parameters); ///<summary>///merges the second and first expression///</summary> static expression<t> compose<t> using the specified merge function (this Expression<t>, expression<t> Second, func<expression, Expression, expression> merge) {//second parameter mapping To the first parameter var map = i. Parameters. Select ((f, i) => new {f, s = second. Parameters[i]}).
ToDictionary (P => p.s, p => p.f); Parameter substitution of the first lambda expression in the second lambda expression parameter var secondbody = Parameterrebinder.replaCeparameters (map, second.
body); Creates a merged LAMBDA expression with a parameter from the first expression return expression.lambda<t> (A. Body, secondbody), the
Parameters); Class Parameterrebinder:expressionvisitor {readonly dictionary<parameterexpression, parameterexpression> m
Ap Parameterrebinder (dictionary<parameterexpression, parameterexpression> map) {This.map = map?? new DICTIONARY&L T
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 to base.
Visitparameter (P);
}
}
}
MyDbContext.CS Code:
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 ();
Modelbuilder.entity<customer> (). Property (c => c.contacttitle). Hasmaxlength (+);
}
HomeController.cs Controller:
public class Homecontroller:controller
{public
actionresult Index ()
{
var model = new Customersviewmodel ()
{
Customers = null,
paginginfo = new Paginginfo ()
{
currentpage=1,
itemsperpage=,
pageoptions = new list<int> () {10,25, MB,
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 = "Your application description page." ";
return View ();
}
Public ActionResult Contacts ()
{
viewbag.message = "Your contact page." ";
return View ();
}
Home View folder:
_customerspartial.cshtml
@model Mesoft.gridview.Models.CustomersViewModel @* here to write down the details of the returned data *@ <span class= "Gridview-data-details" 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.first Ordefault (). CompanyName)) </th> <th class= "sortable" data-sort= "ContactTitle" > @ (html.displaynamefor (x => x.custo Mers. 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" >x</button> <strong> warning!
</strong> no customers to find! ,;/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" > <!--the left portion of the head of the GridView--> <div class= "Col-sm-6" > <div class= "Gridview-search" > <div class= "Search Input-group" > <input class= "Form-control" Placehold er= "Search" type= "search" > <span class= "input-group-btn" > <button class= "btn btn-default" type= "button" &
Gt <span class= "fa fa-search" ></span> <span class= "sr-only" >Search</span> </button> & lt;/span> </div> </div> </div> <!--the head right part of the GridView--> <div class= "Col-sm-6 Text-righ T "> <!--Add any filtering actions here--> @{string[] cityfilters = {" Istanbul "," Trabzon "," Ankara "," Izmir "," Samsun "," Erzu "
Rum "}; Filter by City: <div class= "Btn-group" > <button type= "button" class= "btn btn-primary dropdown-toggle" Data-togg Le= "DropdoWN "> Select City <span class=" caret "></span> </button> <ul class=" Dropdown-menu filter-pare NT "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 cl
ass= "Divider" ></li> <li class= "active" ><a href= "#" class= "filter" data-filter-column= "City" Data-filter-value= "All" >All</a></li> </ul> </div> </div> </div> <!--Gr Idview viewport--> <div class= "Gridview-viewport" id= "ViewPort" @Url. Action (" GetCustomers "," Home ")" data-default-pagesize= "> <div class=" Gridview-canvas "style=" min-height:400px; " > @*data'll Load here*@ </div>
<div class= "Loading GridView Gridview-loader" > <img src= "~/content/images/loading.gif"/> </div> & Lt;/div> <!--The paging area of the GridView--> <div class= "Gridview-footer" > @Html. Displayfor (x => x.paginginfo, "Pa
Ger ") </div> </div>
About.cshtml
@{
viewbag.title = "about";
}
Contact.cshtml
@{
viewbag.title = "Contact";
}
Index.cshtml
@model Mesoft.gridview.Models.CustomersViewModel
@{
viewbag.title = "Home Page";
}
<div class= "Jumbotron" >
Shared folder:
_layout.cshtml
<! DOCTYPE html> <html> <head> <meta charset= "Utf-8"/> <meta name= "viewport" content= "Width=devic" E-width, initial-scale=1.0 "> <title> @ViewBag. Title-gridview Usage Example Application </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 ("Contacts", "Contact", "Home") </li> </ Ul> @* @Html. Partial ("_loginpartial") *@ </div> </div> </div> <div class= "Container Body-cont
Ent "> @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>
Run the results as shown in figure:
3 wonderful topics to be attached:
Asp. NET Control Usage Manual
Asp. NET data-bound controls using totals
Asp. NET controls use totals
The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.