ASP. net mvc 5 is used as the GridView partition, And the gridview

Source: Internet
Author: User

ASP. net mvc 5 is used as the GridView partition, And the gridview

This document uses ASP. net mvc 5 is actually a GridView with the following functions: paging, filtering, sorting, and AJAX non-synchronous upload rows, the external store also supports Responsive Web Design ). The following is the limit 1 line.

ASP. net mvc has many methods for implementing the GridView and paging. This article is an article titled Code Project [1]. Before creating a notebook, you should set up a notebook. paging can be divided into two types: frontend and backend. You should avoid mixing them into one notebook, as shown below:
1. Front-end: refers to the "User Interface", such as the "upper limit" column... .
2. backend: refers to the method of "indexing data", such as using the ROW_NUMBER function of SQL Server, or using the OFFSET-FETCH method of T-SQL, the current information should be presented in the response.

Third-party components used in this article:
1. jQuery datatables: used to handle the preceding "front-end" partition, that is, external tables and user interfaces used to present the Grid table, and interaction with users (in addition to jQuery, but also through bootstrap, CSS and a Flash animation ).
2. datatables. mvc5: used to handle the preceding "backend" segmentation, that is, used to collect data. In addition, it can be avoided to write the paging SQL statement or Stored Procedure by yourself like WebForm. In addition, this component also supports the strongly typed model of the Controller worker.

-------------------------------------------------
In the example below:
Http://files.cnblogs.com/files/WizardWu/170326.zip
For example, if Visual Studio 2015 is used (as long as ASP. net mvc 5 is supported), the SQL Server's Northwind resource is required.
-------------------------------------------------



In example, the rows of rows are shown as faces.

First, add a Web project in VS 2015 and check the MVC example.

Then, in the Models notebook, add an empty C # class Order. cs (This article uses the Orders data table as an example), and manually add it. To present the get/set accessor of each vertex in the GridView, the following formula is used:

Using System. componentModel. dataAnnotations; namespace NorthwindPaging. models {public class Order {public int OrderID {get; set;} [Display (Name = "ID")] public string CustomerID {get; set ;} [Display (Name = "employee ID")] public decimal EmployeeID {get; set;} [Display (Name = "shipping country")] public string ShipCountry {get; set;} [Display (Name = "Courier")] public decimal Freight {get; set ;}}}

In the case of Models/IdentityModels. cs, the relationship function of ASP. NET identity 2.0 is enabled. We add the property Program of the following Order data table:

Public DbSet <Order> Orders {get; set;} // Order of Orders from Orders

Then, in the Controller role, add a blank Controller named OrderController 」.

Appendix: In this example, the Entity Framework concepts, DbSet, DbContext, and other objects and binding functions are used, but the. edmx Entity model samples are not used.

 

Installing jQuery datatables

However, you need to install jQuery datatables through NuGet, as shown in section 2 below.

Plugin 2 install jQuery datatables

After the security is complete, a DataTables resource and related .css;.swf will be generated automatically under the Content and Scripts resources of the case ,. js example.

Next, we will help jQuery datatables to perform the notebook. In App_Start/BundleConfig. cs, add the following two program links:

// jquery datataables js filesbundles.Add(new ScriptBundle("~/bundles/datatables").Include(            "~/Scripts/DataTables/jquery.dataTables.min.js",            "~/Scripts/DataTables/dataTables.bootstrap.js"));// jquery datatables css filebundles.Add(new StyleBundle("~/Content/datatables").Include(          "~/Content/DataTables/css/dataTables.bootstrap.css"));

In Views/Shared/_ Layout. cshtml, add the following two stroke types:

@Styles.Render("~/Content/datatables")@Scripts.Render("~/bundles/datatables")

 

Installing datatables. mvc5

The following figure shows how to install datatables. mvc5 through NuGet.

3. Install datatables. mvc5

After the installation, an additional test of Ables. Mvc. dll will be provided.

Metadata setting

First, in the DefaultConnection string of the Web. config resource, manually add the zookeeper settings of Northwind.

Then, add the following program token in Controllers/OrderController. cs to obtain the information token and token for the later Controller Action method.

private ApplicationDbContext _dbContext;public ApplicationDbContext DbContext{    get    {        return _dbContext ?? HttpContext.GetOwinContext().Get<ApplicationDbContext>();    }    private set    {        _dbContext = value;    }}

 

Initialize jQuery datatables

In the Views/Order item, add a blank "Website" named OrderGridView (or any name ). Then clear all the content of OrderGridView. cshtml (jQuery datatables will generate tags such as head and body), and manually add the following HTML tags:

<Div class = "row"> <div class = "col-md-12"> <div class = "panel-primary list-panel" id = "list-panel"> <div class = "panel-heading list-panel-heading"> 

Then merge rows in OrderGridView. in cshtml, manually add the following program, so that the server-side outputs the response surface from the data volume in AJAX mode, which should present the current information:

@section Scripts{    <script type="text/javascript">        var orderListVM;        $(function () {            orderListVM = {                dt: null,                init: function () {                    dt = $('#orders-data-table').DataTable({                        "serverSide": true,                        "processing": true,                        "ajax": {                            "url": "@Url.Action("Get","Order")"                        },                        "columns": [                            { "title": "Order ID", "data": "OrderID", "searchable": true },                            { "title": "Customer ID", "data": "CustomerID", "searchable": true },                            { "title": "Employee ID", "data": "EmployeeID", "searchable": true },                            { "title": "Ship Country", "data": "ShipCountry", "searchable": true },                            { "title": "Freight", "data": "Freight", "searchable": true }                        ],                        "lengthMenu": [[10, 25, 50, 100], [10, 25, 50, 100]],                    });                }            }            // initialize the datatables            orderListVM.init();        });    </script>}

In the preceding formula, serverSide ": true indicates that paging, filtering, and sorting must be obtained from server-side according to each user operation; instead, all the data that meets the select where condition will be exported at one time, and then processed by client-side (if the amount of data is too large, the efficiency will be dragged down ).
Processing ": true, indicating whether to display the processing surface during data access. The processing effect and Word format at the time of import. If this parameter is not set, the parameter is set to false. LengthMenu indicates the number of data records to be displayed in each region. This example allows users to use the combo box for selection.

 

Installing System. Linq. Dynamic

In this example, the sorting method of Dynamic LINQ is used (not necessary, just for the program handler of the sorting program). This function requires external security. We have passed through NuGet's secure Dynamic LINQ, as shown in section 4 below.


Release 4 Security plugin Dynamic LINQ

 

Compilation of sorting, filtering, and paging functions in render Controller

Next, write the Get Action method in OrderController. The program is as follows:

Public ActionResult Get ([ModelBinder (typeof (ableablesbinder)] IDataTablesRequest requestModel) {IQueryable <Order> query = DbContext. orders; // LINQ to Entites var totalCount = query. count (); // all the Order data tables are 830 bytes # region Filtering (User-Defined keyword search criteria) // Apply filters for searching (DataTables. mvc. search) if (requestModel. search. value! = String. empty) {var value = requestModel. search. value. trim (); // filtering function (bytes must be string, digits int, decimal cannot be set, so ToString () query = query. where (o => o. orderID. toString (). contains (value) | o. customerID. contains (value) | o. employeeID. toString (). contains (value) | o. shipCountry. contains (value) | o. freight. toString (). contains (value);} var filteredCount = query. count (); // All 830 bytes # endregion Filtering # region Sorting var sortedColumns = requestModel. Columns. GetSortedColumns (); var orderByString = String. Empty; foreach (var column in sortedColumns) {orderByString + = orderByString! = String. Empty? ",": ""; OrderByString + = (column. Data) + (column. SortDirection = Column. OrderDirection. Ascendant? "Asc": "desc");} // Dynamic LINQ query = query. OrderBy (orderByString = string. Empty? "OrderID asc": orderByString); // The sort bit and method set by the handler # endregion Sorting # region Paging query = query. skip (requestModel. start ). take (requestModel. length); // Skip: Start index, Take: Number of shards to be renewed (you can select from the drop-down list) int i1 = query. count (); // OFFSET-FETCH or ROW_NUMBER () of the SQL Server used. Over the past few seconds, the 10 rows that should be displayed on the Response Surface are displayed. // Select () reorganize the information we need var data = query. select (order => new {OrderID = order. orderID, CustomerID = order. customerID, EmployeeID = order. employeeID, ShipCountry = order. shipCountry, Freight = order. freight }). toList (); # endregion Paging int i2 = query. count (); // 10 int i3 = data. count (); // 10 int i4 = requestModel. draw; // 1, 2 ,... (Non-linear number) int i5 = requestModel. start; // Start index, where 1st rows are 0, 2nd rows are 10, 4th rows are 30 ,... int i6 = requestModel. length; // 10. tells how many records per page user wants to see which is also retriable by user using combo box int i7 = filteredCount; // 830 bytes int i8 = totalCount; // 830 bytes // data 1: datatables. mvc5's self-contained class DataTablesResponse, number 2: allows http get to access return Json (new DataTablesResponse (requestModel. draw, data, filteredCount, totalCount), JsonRequestBehavior. allowGet );}ActionResult Get ()

This self-generated Get method returns the JsonResult. The first dataset is the self-generated class ableablesresponse of the third-party component Ables. mvc5. If we are in the front-end OrderGridView. cshtml, if the written response to columns is not correct, the GridView can display the data normally. Because jQuery datatables supports Bootstrap, this GridView external store also supports RWD (response-based network, images are automatically released.

GridView interest Culture

The text information in jQuery datatables is in English. to change it to Chinese, you can choose Scripts \ DataTables \ jquery. dataTables. min. in this example, the JavaScript code is modified by hand. The result of the subsequent row is shown in the "show" column in the lower left corner of Example 1.

Post-end segmentation T-SQL Embedding Method

If we start SQL Profiler, check the T-SQL statement that the row was written when the cursor was on the plane, it will be found that LINQ has handled the question of "points" when the resources are being processed. This can avoid the issue of creating your own documents like in the past WebForm era, handle paging SQL statement or Stored Procedure [4].

The OFFSET-FETCH encoding method is automatically referenced in the "split" statement because the database version used by the version engineer is SQL Server 2016. The following side of the T-SQL sentence, points for the regression surface, Grid View first week, the fourth week of the regression method, the starting index points are 0, 30, starting from 0th RMB and 30th RMB, 10 RMB will be generated.

SELECT     [Extent1].[OrderID] AS [OrderID], [Extent1].[CustomerID] AS [CustomerID], [Extent1].[EmployeeID] AS [EmployeeID], [Extent1].[ShipCountry] AS [ShipCountry], [Extent1].[Freight] AS [Freight]    FROM [dbo].[Orders] AS [Extent1] ORDER BY [Extent1].[OrderID] ASC    OFFSET 0 ROWS FETCH NEXT 10 ROWS ONLY 
SELECT     [Extent1].[OrderID] AS [OrderID], [Extent1].[CustomerID] AS [CustomerID], [Extent1].[EmployeeID] AS [EmployeeID], [Extent1].[ShipCountry] AS [ShipCountry], [Extent1].[Freight] AS [Freight]    FROM [dbo].[Orders] AS [Extent1] ORDER BY [Extent1].[OrderID] ASC    OFFSET 30 ROWS FETCH NEXT 10 ROWS ONLY 

 

 

Additional exam articles

[1] GridView with Server Side Filtering, Sorting and Paging in ASP. net mvc 5 (server-side)
Https://www.codeproject.com/Articles/1118363/GridView-with-Server-Side-Filtering-Sorting-and-Pa

[2] Grid with Server Side Advanced Search using JQuery DataTables in ASP. net mvc 5 (server-side)
Https://www.codeproject.com/Articles/1170086/Grid-with-Server-Side-Advanced-Search-using-JQuery

[3] Beginners Guide for Creating GridView in ASP. net mvc 5 (client-side)
Https://www.codeproject.com/Articles/1114208/Beginners-Guide-for-Creating-GridView-in-ASP-NET-M

Related Articles

[4] ASP. NET data paging Article 1-exploring paging principles and the ROW_NUMBER function of SQL Server 2005
Http://www.cnblogs.com/WizardWu/archive/2008/08/02/1258832.html

[5] ASP. NET data paging Part 2-sample download
Http://www.cnblogs.com/WizardWu/archive/2008/08/06/1261589.html
---------------------------------------------

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.