Documente Academic
Documente Profesional
Documente Cultură
43
Essential Grid for ASP.NET MVC Classic
Essential Grid for ASP.NET MVC Classic
Contents
1 Overview 18
1.1 Introduction to Essential Grid for ASP.NET MVC ................................................................. 18
1.2 Prerequisites and Compatibility ........................................................................................... 20
1.3 Documentation .................................................................................................................... 21
3 Getting Started 29
3.1 Getting Started with the Syncfusion MVC Grid ..................................................................... 29
3.1.1 Syncfusion Utilites .................................................................................................. 29
3.1.1.1 Project Template Utility............................................................................... 29
3.1.1.1.1 Creating an MVC4 Razor application with the
Syncfusion Project Template.......................................................... 29
3.1.1.2 Project Migration Utility ............................................................................... 33
3.1.1.2.1 Converting an existing MVC application to a
Syncfusion MVC application........................................................... 33
3.1.2 Adding Grid to the project ....................................................................................... 35
5 How to 927
5.1 Adding a Model to the Application...................................................................................... 927
5.2 Settings for Essential Grid in MVC 4 Application ................................................................ 930
5.3 Strongly Typed View ......................................................................................................... 932
5.3.1 Creating a Strongly Typed View ............................................................................ 932
5.3.2 Creating a Strongly Typed View Manually ............................................................. 934
5.4 Create the ADO.NET Entity Data Model ............................................................................ 935
5.5 Create the Generic Collection Model ................................................................................. 940
5.6 Create the Grid using view customization with Default view ............................................... 943
5.7 How to manually configure the MVC application for Grid .................................................... 945
5.7.1 Creating a Platform Application ............................................................................. 945
5.7.2 Adding Essential Grid to the Application Using ASPX ............................................ 950
5.7.2.1 Adding Reference Assemblies .................................................................. 950
5.7.2.2 Adding Scripts .......................................................................................... 953
5.7.2.3 Adding Codes to the Web.config File ........................................................ 956
5.7.2.4 Add StyleManager and ScriptManager ..................................................... 958
5.7.2.4.1 Adding StyleManager .............................................................. 958
5.7.2.4.2 Adding ScriptManager............................................................. 959
5.7.2.5 Creating the Grid control .......................................................................... 959
5.7.2.5.1 Through GridBuilder ................................................................ 959
5.7.2.5.2 Through GridPropertiesModel ................................................. 961
5.7.3 Adding Essential Grid to the Application Using Razor ........................................... 965
5.7.3.1 Adding Reference Assemblies .................................................................. 966
5.7.3.2 Adding Scripts .......................................................................................... 968
5.7.3.3 Adding Codes to the Web.config File ........................................................ 971
5.7.3.4 Adding Codes to the Views Web.config file (Views\Web.config) ................ 974
5.37 How to: Save the Grid Content using an External Button. ................................................ 1060
5.38 How to: Change dropdown to textbox cell for particular cells when celledit type is
dropdown ........................................................................................................................ 1060
5.39 How to: Hide MasterCellCollapse/Expand in Hierarchy Grid ............................................. 1062
5.40 How to: Hide GroupHeaderArea when Grouping is defined in code.................................. 1063
5.41 How to: Assign datasource for a DropdownEdit at clientside ............................................ 1064
5.42 How to: Update the cell value at client side ...................................................................... 1067
5.43 How to: Change entire column values in client side.......................................................... 1068
5.44 How to: Check which column is filtered in the OnActionSuccess Client-Side
event. .............................................................................................................................. 1074
5.45 How to: Use waiting popup of grid, in Client-Side event of the grid in toolbar
button?............................................................................................................................ 1075
5.46 How to: Add a hyperlink to unbound Column of MVC Grid ............................................... 1077
5.47 How to: Remove up and down arrows in numeric textbox ................................................ 1078
5.48 How to: Set grouping initially with datatable elements ...................................................... 1080
5.49 How to: Apply manual filtering to the grid with Queryparam.............................................. 1081
5.50 How to: Avoid the duplicate row insertion and display error message ............................... 1083
5.51 How to: Import an Excel(.xlsx) file into Grid ...................................................................... 1085
5.52 How to: Load only required rows from database, instead of loading all data. .................... 1087
5.53 How to: Enum Dropdown in grid ...................................................................................... 1087
5.54 How to: Store the Grouping, Sorting, Filtering and Columns Info in XML .......................... 1088
5.55 How to: Multiple Grid not showing on JQuery tabs ........................................................... 1091
5.56 How to: Preventing Grid focus at the top of grid ............................................................... 1093
5.57 How to: Programmatically filter a column ......................................................................... 1094
5.58 How to: Set the number of records per page and for subsequent pages, by
default. ............................................................................................................................ 1101
5.59 How to: Set Image Column using Url.Content .................................................................. 1102
5.60 How to: Bind Javascript onkeypress event on editcell ...................................................... 1103
5.61 How to: Click automation of the edit dialog save button.................................................... 1104
5.62 How to: Use AntiForgeryToken with Grid Editing.............................................................. 1106
1 Overview
1.1 Introduction to Essential Grid for ASP.NET MVC
Essential Grid for ASP.NET MVC is a feature-rich control that provides extensive appearance
customization options with support for grouped records. With Essential Grid for ASP.NET MVC,
you can create a grid with a highly customizable look and feel. This grid is very useful for
generating complex grid-based reports with rich formatting. It supports paging, sorting, grouping,
filtering, and editing features. It also supports a JSON mode in which you can handle all the
operations like paging and sorting. The performance of these operations in the JSON mode will
be much faster than if the grid were to handle them. Essential Grid generates clean HTML in
compliance with XHTML 1.0. It supports any kind of IEnumerable data source. It uses LINQ data
retrieval techniques for handling data sources, and offers high performance.
Developers can make use of Essential Grid to generate complex grid-based reports with rich
formatting.
At its core, the grid functions as a very efficient display engine for tabular data that can be
customized down to the cell level. It does not make any assumptions on the structure of the data
(many grid controls implemented as straight data-bound controls make such explicit
assumptions). This leads to a very flexible design that can be easily adapted to a variety of tasks
including the display of completely unstructured data and the display of structured data from a
database.
The display system also hosts a powerful and complete styles architecture. Settings can be
specified at the cell level or at higher levels using parent styles that are referred to as base styles.
Base styles can affect groups of cells. Cell level settings override any higher level settings and
enable easy customization right down to that level.
Key Features
Some important features of Grid for MVC are listed below.
Highly customizable look and feel—Fill the Grid control with data from any data source
and render it as an image in a browser.
Data sources—Bind the Grid control with any data source. For example, all IEnumerable
data sources.
Navigation—Offers complete navigational support for navigating between the grid cells,
rows, and pages.
Sorting and grouping—Supports n levels of sorting and grouping.
Filtering—Offers Excel-like filtering for filter data.
Editing—Offers three editing modes for inserting, editing, and deleting records in a grid.
Conditional formatting—Provides an option to format grid cells based on a certain
condition.
Drag-and-drop records—Exposes flexible client-side events to drag-and-drop grid
records over other HTML elements on the page.
Summary support—Offers options for specifying summary rows and columns.
Column formatting—Columns can be formatted directly from view.
JSON mode—Offers support for JSON mode. You can handle operations and send the
data in JSON mode to view data which is displayed in ASP.NET 4.0 templates.
Unbound columns—Offers option for specifying unbound columns.
Drag-and-drop support—Allows you to drag any column and drop it at any position in the
grid, allowing columns to be repositioned at the required place.
Resize rows and columns—Grid provides option for resizing the rows and columns.
Hide rows and columns—The grid provides support to hide or unhide a range of rows and
columns.
Selection modes—Essential Grid offers different kinds of selections such as row only,
column only, cell only for the selection of a particular row, or an entire grid selection.
Complete AJAX support—Enables faster output.
Complete XHTML compliance—Provides the best results on all browsers.
Prerequisites
The prerequisites details are listed below:
Table 1: Prerequisites Table
Compatibility
The compatibility details are listed below:
Table 2: Compatibility Table
1.3 Documentation
Syncfusion provides the following documentation segments to provide all the necessary
information pertaining to the Grid control.
The appropriate directory usually where the project file is saved must be marked as an
Application in IIS.
The Syncfusion assemblies can be deployed in either the server's GAC (Global Assembly Cache)
or the application's Bin folder.
General Instructions
Data Files
If you have XML, .mdb, or other data files, ensure that they have sufficient security permissions.
The Authenticated Users should have access to the files and the directory to give the ASP.NET
code enough permission to open the file at run time.
Supporting Netscape/Firefox/Mozilla
Ensure that the Machine.config's (of the deployed system) <browserCaps> section includes
appropriate entries for Mozilla, and so on. The default entries consider these browsers as
downlevel and hence will not render Syncfusion and your controls properly.
1. Syncfusion assemblies in the GAC (Global Assembly Cache) and application running in
medium trust.
1.
This means the Syncfusion assemblies are running in full trust which is explained in Default
Deployment Pattern. This scenario is fully supported and there are no additional steps
necessary.
2. Syncfusion assemblies in the application Bin folder and application running in medium
trust.
This means both the Syncfusion assemblies and the application code are running in partial
trust which is explained in Fast Deployment Pattern. In this case, the control’s
DeprecateFunctionalityToRunInPartialTrust property should be turned on for the control
to work properly. This also means some features might not be available. See the control's
documentation for more info.
1. Delete the Syncfusion assembly GAC entries in your development machine. The
referenced assemblies will be copied over to the Bin folder.
2. The Web.config file should be configured according to the referenced DLLs. For more
information on the Web.config file configuration please refer to the following link:
Configuring Web.Config file
Note: If you do not want to delete Syncfusion assembly GAC entries then in the Web.config file
please remove the Culture, Version, and PublicKeyToken attributes used in all <assemblies>,
<httpHandlers>, and <handlers> nodes.
2.1.3 DLL
The following assemblies need to be referenced in your application in order to use Essential Grid
for ASP.NET MVC.
Syncfusion.Core.dll
Syncfusion.Grid.Mvc.dll
Syncfusion.Linq.Base.dll
Syncfusion.Shared.Mvc.dll
Syncfusion.Compression.Base.dll
Syncfusion.XlsIO.Mvc.dll
Syncfusion.DocIO.Mvc.dll
Syncfusion.Pdf.Base.dll
AjaxMin.dll
Syncfusion.Theme.Base.dll
Note: Theme source is included from Essential Studio version 10.3.0.43. Therefore, reference of
“Syncfusion.Theme.Base” dll must be included in applications to load themes for the controls.
This section covers the location of the installed samples and describes the procedure to run the
samples through the sample browser and online. It also provides the location of the source code.
<Install Location>\Syncfusion\EssentialStudio\<Version
Number>\MVC\Grid.MVC\Samples\3.5
Viewing Samples
In the Dashboard window, click ASP.NET MVC in the Essential Studio panel and click Run
Local Samples. The ASP.NET MVC Sample Browser window is displayed.
Note: You can view the samples in any of the following three ways:
Click Grid in the other ASP.NET MVC products. The Grid samples are displayed.
The default location of the Essential Grid for MVC source code is:
3 Getting Started
3.1 Getting Started with the Syncfusion MVC Grid
The Syncfusion MVC Grid is a full-featured Grid control built specifically for ASP.NET MVC.
Integrating the Grid into your application involves making configuration changes and adding the
required code into your application controllers and views. This document will provide the
necessary information for this and also explain the changes as needed.
Syncfusion provides two utilities that can help you with integrating the Grid into your MVC
application:
1. Project creation template utility
2. Project migration utility
Both of the above utilities are integrated into Visual Studio 2010 and 2012. We will be reviewing
these utilities in the document as well, but the focus will be on the manual changes that need to
be made to the application project as these utilities only automate making these changes.
Configuration of the MVC project to enable the Syncfusion Grid can be done using the Syncfusion
Project Template utility.
Create a new MVC project:
3. In the Templates panel, expand the Syncfusion list and then click Web.
4. Select Syncfusion ASP.NET MVC 4 Web Application (C#) in the main window.
5. Enter an appropriate application name. The Syncfusion Product Selection dialog box is
displayed.
8. Select a theme.
9. Click Done. Now the application is ready to be added to the Syncfusion MVC Grid as
explained in the section “Adding Grid to the project”.
2.
6. Select a theme.
7. Now the application is ready for adding the Syncfusion MVC Grid as explained in the
following section, “Adding Grid to the project”.
The Grid requires a model for binding the data. Please create a model and add it into the
application (Refer to How to > Adding a Model to the Application).
The Syncfusion MVC Grid can be added to a View. The next step would be to create a create a
strongly typed view (Refer to How to > Strongly Typed View).
The code below shows how the Grid can be instantiated in the View and bound to the Model.
Razor:
Index.cshtml
@{Html.Syncfusion().Grid<EditableOrder>("OrderGrid")
.Caption("Orders")
.Datasource(Model)
.ActionMode(ActionMode.Server)
.EnablePaging()
.EnableGrouping()
.EnableSorting()
.Column(column =>
{
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.CustomerID).HeaderText("Customer
ID");
column.Add(p => p.ShipCity).HeaderText("ShipCity");
column.Add(p =>
p.ShipCountry).HeaderText("ShipCountry");
column.Add(p => p.Verified).HeaderText("Verified");
}).Render();
}
ASPX:
Index.aspx
<%=Html.Syncfusion().Grid< EditableOrder >("SampleGrid")
.Datasource(Model)
.EnablePaging()
.ActionMode(ActionMode.Server)
.EnableSorting()
.Caption("Orders")
.Column(column =>
{
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.CustomerID).HeaderText("Customer
ID");
column.Add(p => p.ShipCity).HeaderText("ShipCity");
column.Add(p =>
p.ShipCountry).HeaderText("ShipCountry");
column.Add(p => p.Verified).HeaderText("Verified");
}) %>
The last step in adding Grid to the project is to add two action methods in the HomeController
(one for loading the view and one for handling the grid paging and sorting actions). The action
methods populate the Model created and pass them to the View.
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
Sample links:
VS 2012/ MVC4 / Razor sample: sample-vs2012.zip
VS2010/ MVC4 / Razor sample: sample-vs2010.zip
This section discusses all the concepts and features of the Grid control under the following sub-
sections. All the topics provide you with complete information about the concepts and give you
the step-by-step procedures involved while working with the MVC architecture.
Reference
You can refer to the installation samples at the following location. Individual samples are available
for every concept.
<Install Location>\Syncfusion\EssentialStudio\<Version Number>\MVC\Grid.MVC\Samples\3.5
The Grid control handles data presentation operations like paging, grouping, filtering, editing and
sorting, or you can perform those operations. But this mode of action for the Grid control is
decided using the ActionMode property whose options are described in the following table.
Essential Grid supports two kinds of action modes.
Properties
Property Description Type of Value it accepts
property
ActionMode Used to set the action mode of the control. Enum ActionMode.Server
Server—All the operations like (or)
sorting,filtering, editing, paging, and grouping
are handled by Essential Grid itself (by ActionMode.JSON
default).
JSON (JavaScript Object Notation)—User
has to handle the operations. The only
possible operations are paging, filtering,
editing, grouping, and sorting.
Methods
Method Parameters Return type Descriptions
ActionMode(ActionMode actionMode IGridBuilder<T> Used to set the
actionMode) action mode to
control.
View [ASPX]
<%=Html.Syncfusion().Grid<MvcSampleApplication.Models.Order>("Fla
tGrid")
.Datasource(Model)
.EnablePaging()
.EnableSorting()
.ActionMode(ActionMode.Server)
.Column( column => {
column.Add(c => c.OrderID).HeaderText("Order ID");
column.Add(c => c.CustomerID).HeaderText("Customer
ID");
column.Add(c => c.EmployeeID).HeaderText("Employee
ID");
column.Add(c => c.OrderDate).HeaderText("Order
Date").Format("{OrderDate:dd/mm/yyyy}");
column.Add(c => c.Freight).HeaderText("Freight");
})
%>
View [cshtml]
@{
Html.Syncfusion().Grid<MvcSampleApplication.Models.Order>("Flat
Grid")
.Datasource(Model)
.EnablePaging()
.EnableSorting()
.ActionMode(ActionMode.Server)
.Column( column => {
column.Add(c => c.OrderID).HeaderText("Order ID");
column.Add(c => c.CustomerID).HeaderText("Customer
ID");
/// <summary>
/// Used to bind the Grid.
/// </summary>
/// <returns>View page, it displays the Grid</returns>
public ActionResult Index()
{
var data = new NorthwindDataContext().Orders.Take(200);
return View(data);
}
5. In order to work with paging and sorting actions, create a Post method for Index actions
and bind the data source to the grid as shown in the following code.
Controller
/// <summary>
/// Paging/sorting Requests are mapped to this method. This
method invokes the HtmlActionResult
/// from the grid. Required response is generated.
/// </summary>
/// <param name="args">Contains paging properties. </param>
/// <returns>
/// HtmlActionResult returns the data displayed on the grid.
/// </returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new
NorthwindDataContext().Orders.Take(200);
return data.GridActions<Order>();
}
1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. Add the following code in the Index.aspx file to create the Grid control in the view.
View [ASPX]
<%=Html.Syncfusion().Grid<MvcSampleApplication.Models.Order>("Fla
tGrid","GridModel",
column => {
column.Add(c => c.OrderID).HeaderText("Order
ID");
column.Add(c =>
c.CustomerID).HeaderText("Customer ID");
column.Add(c =>
c.EmployeeID).HeaderText("Employee ID");
column.Add(c =>
c.OrderDate).HeaderText("Order
Date").Format("{OrderDate:dd/mm/yyyy}");
column.Add(c =>
c.Freight).HeaderText("Freight");
}) %>
View [cshtml]
@(
Html.Syncfusion().Grid<MvcSampleApplication.Models.Order>("FlatGrid","G
ridModel",
column =>{
column.Add(c => c.OrderID).HeaderText("Order ID");
column.Add(c => c.CustomerID).HeaderText("Customer
ID");
column.Add(c => c.EmployeeID).HeaderText("Employee
ID");
column.Add(c => c.OrderDate).HeaderText("Order
Date").Format("{OrderDate:dd/mm/yyyy}");
column.Add(c => c.Freight).HeaderText("Freight");
}))
4. Create a GridPropertiesModel in the Index method. Assign grid properties in this model
and pass the model from controller to view using the ViewData class as shown below:
5. In order to work with paging and sorting actions, create a Post method for Index actions
and bind the data source to the grid as shown in the following code.
Controller
/// <summary>
/// Paging/sorting Requests are mapped to this method. This method
invokes the HtmlActionResult
/// from the Grid. Required response is generated.
/// </summary>
/// <param name="args">Contains paging properties </param>
/// <returns>
/// HtmlActionResult returns the data displayed on the grid.
/// </returns>
[AcceptVerbs(HttpVerbs.Post)]
JSON (JavaScript Object Notation) is a lightweight data interchange format for serialization of
structured data. It defines a small set of formatting rules for the portable representation of
structured data. It is human readable, platform independent, and has a wide availability of
implementations. You will use this JSON format to exchange data in the MVC architecture.
In JSON mode, the only possible operations are paging, filtering, editing, grouping, and sorting.
Operation in the JSON mode can be handled by you. The PagingParams instance holds the
essential information about the current request. ASP.NET client-side templates have the
responsibility of generating HTML from JSON. This mode gives better performance than the
server mode. The initial rendering is done in the server mode only.
1. Create a model in the application (refer to How to > Adding a Model to the Application).
2. Create a strongly typed view (refer to How to > Strongly Typed View).
3. Create the Grid control in the view and configure its properties.
4. Set action mode as JSON using the ActionMode method.
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("JsonGrid")
.Datasource(Model)
.Caption("Orders")
.ActionMode(ActionMode.JSON)
.EnablePaging()
.EnableSorting()
.Column(column => {
column.Add(p => p.CustomerID).HeaderText("Customer ID");
column.Add(p => p.EmployeeID).HeaderText("Employee ID");
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(P => P.ShipCountry).HeaderText("Ship Country");
column.Add(p => p.ShipCity).HeaderText("Ship City");
})
%>
View [cshtml]
@{ Html.Syncfusion().Grid<Order>("JsonGrid")
.Datasource(Model)
.ActionMode(ActionMode.JSON)
.Caption("Orders")
.EnablePaging()
.EnableSorting()
.Column(column => {
column.Add(p => p.CustomerID).HeaderText("Customer ID");
column.Add(p => p.EmployeeID).HeaderText("Employee ID");
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(P => P.ShipCountry).HeaderText("Ship Country");
column.Add(p => p.ShipCity).HeaderText("Ship City");
}).Render();
6. In order to work with paging and sorting, create a post method for index actions and bind the
data source to the grid as given in the following code sample.
Controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new NorthwindDataContext().Orders.ToList();
return data.GridJSONActions<Order>();
}
3. 1. Create a model in the application (refer to How to > Adding a Model to the Application).
4. 2. Create a strongly typed view (refer to How to > Strongly Typed View).
5. 3. Create the Grid control in the view and configure its properties.
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("JsonGrid","GridModel",column => {
column.Add(p => p.CustomerID).HeaderText("Customer ID");
column.Add(p => p.EmployeeID).HeaderText("Employee ID");
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(P => P.ShipCountry).HeaderText("Ship Country");
column.Add(p => p.ShipCity).HeaderText("Ship City");
})%>
View [cshtml]
@( Html.Syncfusion().Grid<Order>("JsonGrid","GridModel",column => {
column.Add(p => p.CustomerID).HeaderText("Customer ID");
column.Add(p => p.EmployeeID).HeaderText("Employee ID");
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(P => P.ShipCountry).HeaderText("Ship Country");
column.Add(p => p.ShipCity).HeaderText("Ship City");
}) )
/// <summary>
/// Used to bind the grid.
/// </summary>
/// <returns>View page, it displays the grid.</returns>
public ActionResult Index()
{
GridPropertiesModel<Order> model = new
GridPropertiesModel<Order>()
{
DataSource = new NorthwindDataContext().Orders.Take(200).
ToList(),
Caption = "Orders",
AllowPaging = true,
AllowSorting = true,
ActionMode = ActionMode.JSON
};
ViewData["GridModel"] = model;
return View();
}
5. In order to work with paging and sorting, create a Post method for Index actions and bind the
data source to the grid as given in the following code sample.
Controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new
NorthwindDataContext().Orders.Take(200).ToList();
return data.GridJSONActions<Order>();
}
The following table contains some data binding properties and their corresponding descriptions:
Property
Property Description Type of Value it Any other
property accepts dependencies/sub-
properties associated
DataSource Gets or sets IEnumerable Any NA
DataSource for the IEnumerable
Grid control data.
Method
Method Parameters Return type Descriptions
Datasource IEnumerable IGridBuilder<T> Used to set data source to
(IEnumerable<T>) datasource the Grid control.
1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. In the view you can use its Model property in Datasource() in order to bind the data
source.
View [ASPX]
<%=Html.Syncfusion().Grid<Product>("Product_grid")
.Datasource(Model)
.Caption("Products")
.Column( column =>
{
column.Add(p =>
p.ProductID).HeaderText("Product ID");
column.Add(p =>
p.ProductName).HeaderText("Product Name");
column.Add(P =>
P.QuantityPerUnit).HeaderText("Quantity Per Unit");
column.Add(p =>
p.SupplierID).HeaderText("Supplier ID");
})
.EnablePaging()
.EnableSorting()
%>
View [cshtml]
@{ Html.Syncfusion().Grid<Product>("Product_grid")
.Datasource(Model)
.Caption("Products")
.Column( column =>
{
column.Add(p =>
p.ProductID).HeaderText("Product ID");
column.Add(p =>
p.ProductName).HeaderText("Product Name");
column.Add(P =>
P.QuantityPerUnit).HeaderText("Quantity Per Unit");
column.Add(p =>
p.SupplierID).HeaderText("Supplier ID");
})
.EnablePaging()
.EnableSorting()
Render();
}
/// <summary>
/// Used to bind the grid.
/// </summary>
/// <returns>View page, it displays the grid.</returns>
public ActionResult Index()
{
var data = new NorthwindDataContext().Products;
return View(data);
}
5. In order to work with paging andsorting actions, create a Post method for Index actions and
bind the data source to the grid as shown in the following code.
Controller
/// <summary>
/// Paging/sorting requests are mapped to this method. This
method invokes the HtmlActionResult
/// from the grid. The required response is generated.
/// </summary>
/// <param name="args">Contains paging properties.</param>
/// <returns>
/// HtmlActionResult returns the data displayed on the grid.
/// </returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new NorthwindDataContext().Products;
return data.GridActions<Order>();
}
1. Create a model in the application (refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (refer to How to>Strongly Typed View).
3. Add the following code in the Index.aspx file to create the Grid control in the view.
View [ASPX]
<%=Html.Syncfusion().Grid<Product>("Product_Grid","GridMode
l", column=> {
column.Add(p => p.ProductID).HeaderText("Product
ID");
column.Add(p => p.ProductName).HeaderText("Product
Name");
column.Add(P =>
P.QuantityPerUnit).HeaderText("Quantity Per Unit");
column.Add(p => p.SupplierID).HeaderText("Supplier
ID");
})%>
View [cshtml]
@(
Html.Syncfusion().Grid<MvcSampleApplication.Models.Order>("Product_Grid
","GridModel",
column=> {
column.Add(p => p.ProductID).HeaderText("Product
ID");
column.Add(p => p.ProductName).HeaderText("Product
Name");
column.Add(P =>
P.QuantityPerUnit).HeaderText("Quantity Per Unit");
4. Create a GridPropertiesModel in the Index method. Bind the data source using the
Datasource property and pass the model from controller to view using the ViewData class
as shown in the following code.
public ActionResult Index()
{
GridPropertiesModel<Product> model = new
GridPropertiesModel<Product>()
{
DataSource=new NorthwindDataContext().Products,
Caption="Product",
AllowPaging = true,
AllowSorting = true
};
ViewData["GridModel"] = model; // Pass the model from
controller to view using ViewData.
return View();
}
5. In order to work with paging and sorting actions, create a Post method for Index actions
and bind the data source to the grid as given in the code below.
Controller
/// <summary>
/// Paging/sorting requests are mapped to this method. This
method invokes the HtmlActionResult
/// from the grid. The required response is generated.
/// </summary>
/// <param name="args">Contains paging properties.</param>
/// <returns>
/// HtmlActionResult returns the data displayed on the grid.
/// </returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new NorthwindDataContext().Products;
return data.GridActions<Product>();
}
The Entity Framework supports an Entity Data Model (EDM) for defining data at both the storage
and conceptual level and also mapping between the two. It also enables you to program directly
against the data types defined at the conceptual level as common language runtime (CLR)
objects. The Entity Framework provides tools to generate an EDM and the related CLR objects
based on an existing database. This reduces much of the data access code that is required to
create object-based data application and services. This makes it faster to create object-oriented
data applications and services from an existing database.
The Entity Framework enables you to avoid the tedious work of building your data access classes
by hand. Entity Framework applications can run on any computer on which the .NET Framework
3.5 Service Pack 1 (SP1) is installed.
Most applications are currently written on top of relational databases. At some point, these
applications will have to interact with the data represented in a relational form.Database schemas
are not always ideal for building applications and the conceptual models of applications differ
from the logical models of databases. The Entity Data Model (EDM) is a conceptual data model
that can be used to model the data of a particular domain so that applications can interact with
data as entities or objects.
Properties
Property Description Type of Value it Any other
property accepts dependencies/sub-
properties
associated
DataSource Gets or sets IEnumerable Any None
the data source IEnumerable
for the Grid data.
control.
Methods
Data can be bound by customizing the view. To do so, there are the six steps involved:
1. Create an Entity model in an application (see Creating the ADO.NET Entity Data Model).
2. Create a strongly typed view (see Creating a Strongly Typed View).
3. In the view, use the Model property in Datasource to bind the data source.
View [ASPX]
<%=Html.Syncfusion().Grid<employee>("EntityGrid")
.Datasource(Model)
.Caption("Employee Details")
.AutoFormat(Skins.Sandune)
.EnablePaging()
.EnableSorting()
.Column(cols =>
{
cols.Add(c => c.emp_id).HeaderText("Employee ID");
cols.Add(c => c.fname).HeaderText("First Name");
cols.Add(c => c.lname).HeaderText("Last Name");
cols.Add(c => c.minit).HeaderText("Min");
cols.Add(c => c.hire_date).HeaderText("Ship
City").Format("{hire_date:dd/mm/yyyy}");
})
%>
View [cshtml]
@{ Html.Syncfusion().Grid<employee>("EntityGrid")
.Datasource(Model)
.Caption("Employee Details")
.AutoFormat(Skins.Sandune)
.EnablePaging()
.EnableSorting()
.Column(cols =>
{
cols.Add(c => c.emp_id).HeaderText("Employee ID");
cols.Add(c => c.fname).HeaderText("First Name");
cols.Add(c => c.lname).HeaderText("Last Name");
cols.Add(c => c.minit).HeaderText("Min");
cols.Add(c => c.hire_date).HeaderText("Ship
City").Format("{hire_date:dd/mm/yyyy}");
}).Render();
}
Controller
/// <summary>
/// Used for rendering the grid initially.
/// </summary>
/// <returns>View page; it displays the grid.</returns>
public ActionResult Index()
{
var data = new PUBSEntities().employees;
return View(data);
}
5. In order to work with paging and sorting actions, create a Post method for the Index actions
and bind the data source to the grid, as seen in the code below.
Controller
/// <summary>
/// Sorting/paging requests are mapped to this method.
/// This method invokes the HtmlActionResult from the grid.
/// The required response is generated.
/// </summary>
/// <returns>HtmlActionResult returns the data displayed on the
grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
6. Run the application; the grid will then appear as seen in the following image.
Data can be bound by using the GridPropertiesModel. To do so, there are five steps involved:
1. Create an Entity model in the application (see Creating the ADO.NET Entity Data Model).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. Create a grid control in the view by adding the following code in the Index.aspx file.
View [ASPX]
View [cshtml]
4. Create a GridPropertiesModel in the Index method. Assign grid properties in this model
and pass the model from controller to view using the ViewData class.
5. In order to work with paging and sorting actions, create a Post method for the Index actions
and bind the data source to the grid.
Controller
/// <summary>
/// Paging/sorting requests are mapped to this method. This
method invokes the HtmlActionResult
/// from the grid. Required response is generated.
/// </summary>
/// <param name="args">Contains paging properties. </param>
/// <returns>
/// HtmlActionResult returns the data displayed on the grid.
/// </returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new PUBSEntities().employees;
return data.GridActions<employee>();
6. Run the application; the grid will then appear as seen in the following image.
1. Create a model in the application (Refer to How to>Creating the Generic Collection Model).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. In the view you can use its Model property in Datasource in order to bind the data source.
View [ASPX]
<%=Html.Syncfusion().Grid<Student>("StudentGrid")
.Datasource(Model)
.Caption("Student List")
.EnablePaging()
.EnableSorting()
.Column( column => {
column.Add(p => p.UniversityCode).HeaderText("University
Code");
column.Add(p => p.Title).HeaderText("Course Title");
column.Add(P => P.Duration).Format("{Duration} hrs");
column.Add(p =>
p.CourseFees).Format("{CourseFees:c}").HeaderText("Course Fees");
column.Add(p => p.CGPA);
})
%>
View [cshtml]
@{ Html.Syncfusion().Grid<Student>("StudentGrid")
.Datasource(Model)
.Caption("Student List")
.EnablePaging()
.EnableSorting()
.Column( column => {
column.Add(p => p.UniversityCode).HeaderText("University
Code");
column.Add(p => p.Title).HeaderText("Course Title");
column.Add(P => P.Duration).Format("{Duration} hrs");
column.Add(p =>
p.CourseFees).Format("{CourseFees:c}").HeaderText("Course Fees");
column.Add(p => p.CGPA);
}).Render();
}
Controller
/// <summary>
/// Used to bind the Grid.
/// </summary>
/// <returns>View page, it displays the Grid</returns>
public ActionResult Index()
{
var data = new StudentDataContext().Student.Take(200);
return View(data);
}
5. In order to work with paging and sorting actions, create a Post method for Index actions
and bind the data source to the grid as shown in the code below.
Controller
/// <summary>
/// Paging/sorting requests are mapped to this method. This
method invokes the HtmlActionResult
/// from the grid. Required response is generated.
/// </summary>
/// <param name="args">Contains paging properties. </param>
/// <returns>
/// HtmlActionResult returns the data displayed on the grid.
/// </returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new
StudentDataContext().Student.Take(200);
return data.GridActions<Student>();
}
1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. Add the following code in the Index.aspx file to create the Grid control in the view.
View [ASPX]
<%=Html.Syncfusion().Grid<Student>("StudentGrid", "GridModel",
column =>
{
column.Add(p =>
p.UniversityCode).HeaderText("University Code");
View [cshtml]
@( Html.Syncfusion().Grid<Student>("StudentGrid", "GridModel",
column =>
{
column.Add(p =>
p.UniversityCode).HeaderText("University Code");
column.Add(p => p.Title).HeaderText("Course
Title");
column.Add(P => P.Duration).Format("{Duration}
hrs");
column.Add(p =>
p.CourseFees).Format("{CourseFees:c}").HeaderText("Course Fees");
column.Add(p => p.CGPA);
}))
4. Create a GridPropertiesModel in the Index method. Bind the data source using the
Datasource property and pass the model from controller to view using the ViewData class
as given below.
public ActionResult Index()
{
GridPropertiesModel<Student> model = new
GridPropertiesModel<Student>()
{
DataSource = new StudentDataContext().Student.Take(200),
Caption = "Student List",
AllowPaging = true,
AllowSorting = true
};
ViewData["GridModel"] = model; // Pass the model from
controller to view using ViewData.
return View();
}
5. In order to work with paging and sorting actions, create a Post method for Index actions
and bind the data source to the grid as shown in the following code.
Controller
/// <summary>
/// Paging/sorting requests are mapped to this method. This
method invokes the HtmlActionResult
/// from the grid. Required response is generated.
/// </summary>
/// <param name="args">Contains paging properties.</param>
/// <returns>
/// HtmlActionResult returns the data displayed on the grid.
/// </returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new
StudentDataContext().Student.Take(200);
return data.GridActions<Student>();
}
Essential Grid supports adding unbound column through IRootGridColumnBuilder in the view.
While using unbound columns you will be unable to perform sorting, grouping, and filtering
functionalities.
Methods
1. Create a model in the application (refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (refer to How to>Strongly Typed View).
3. In the view you can use its Model property in Datasource to bind the data source.
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("OrderGrid")
.Datasource(Model)
.Caption("Orders Grid")
%>
View [cshtml]
@{ Html.Syncfusion().Grid<Order>("OrderGrid")
.Datasource(Model)
.Caption("Orders Grid")
.Render();
}
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("OrderGrid")
.Datasource(Model)
.Caption("Orders Grid")
.Column( column => {
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.CustomerID).HeaderText("Customer ID");
@{ Html.Syncfusion().Grid<Order>("OrderGrid")
.Datasource(Model)
.Caption("Orders Grid")
.Column( column => {
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.CustomerID).HeaderText("Customer ID");
column.Add(p => p.ShipCountry).HeaderText("Ship Country");
column.Add(p => p.ShipName).HeaderText("Ship Name");
column.Add(p =>
p.Freight).HeaderText("Freight").Format("{Freight:c}");
}).Render();
}
5. In column mapping, add the unbound column using the Add(string) method. In this case a
“Delete” column has been added as an unbound column which is used to delete records in
the grid.
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("OrderGrid")
.Datasource(Model)
.Caption("Orders Grid")
.Column( column => {
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.CustomerID).HeaderText("Customer ID");
column.Add(p => p.ShipCountry).HeaderText("Ship
Country");
column.Add(p => p.ShipName).HeaderText("Ship Name");
column.Add(p =>
p.Freight).HeaderText("Freight").Format("{Freight:c}");
column.Add("Delete").HeaderText("Delete
Record").Format("<a class=\"TemplateCell\"
href=\"DeleteRecord?id={OrderID}\">Delete</a>");
})
%>
View [cshtml]
@{ Html.Syncfusion().Grid<Order>("OrderGrid")
.Datasource(Model)
.Caption("Orders Grid")
.Column( column => {
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.CustomerID).HeaderText("Customer ID");
column.Add(p => p.ShipCountry).HeaderText("Ship
Country");
column.Add(p => p.ShipName).HeaderText("Ship Name");
column.Add(p =>
p.Freight).HeaderText("Freight").Format("{Freight:c}");
column.Add("Delete").HeaderText("Delete
Record").Format("<a class=\"TemplateCell\"
href=\"DeleteRecord?id={OrderID}\">Delete</a>");
}).Render();
}
6. Add two methods (one for loading the view and one for handling the delete actions).
Controller
/// <summary>
/// Used to bind the grid.
/// </summary>
/// <returns>View page; it displays the grid.</returns>
public ActionResult Index()
{
var data = new NorthwindDataContext().Orders.Take(15);
return View(data);
}
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult DeleteRecord(int id)
{
NorthwindDataContext context = new NorthwindDataContext();
Order order = (Order)context.Orders.Single(p => p.OrderID
== id);
context.Orders.DeleteOnSubmit(order);
context.SubmitChanges();
return RedirectToAction("Index");
}
<%=Html.Syncfusion().Grid<Order>("UnBoundColumn_Grid", "GridModel",
column =>
{
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.CustomerID).HeaderText("Customer ID");
column.Add(p => p.ShipCountry).HeaderText("Ship
Country");
column.Add(p => p.ShipName).HeaderText("Ship Name");
column.Add(p =>
p.Freight).HeaderText("Freight").Format("{Freight:c}");
})%>
View [cshtml]
@( Html.Syncfusion().Grid<Order>("UnBoundColumn_Grid", "GridModel",
column =>
{
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.CustomerID).HeaderText("Customer ID");
column.Add(p => p.ShipCountry).HeaderText("Ship
Country");
column.Add(p => p.ShipName).HeaderText("Ship Name");
column.Add(p =>
p.Freight).HeaderText("Freight").Format("{Freight:c}");
}))
4. In column mapping, add the unbound column using the Add(string) method. In this case a
“Delete” column has been added as an unbound column which is used to delete records in
the grid.
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("UnBoundColumn_Grid", "GridModel",
column =>
{
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.CustomerID).HeaderText("Customer ID");
column.Add(p => p.ShipCountry).HeaderText("Ship
Country");
column.Add(p => p.ShipName).HeaderText("Ship Name");
column.Add(p =>
p.Freight).HeaderText("Freight").Format("{Freight:c}");
column.Add("Delete").HeaderText("Delete
Record").Format("<a class=\"TemplateCell\"
href=\"DeleteRecord?id={OrderID}\">Delete</a>");
})%>
View [cshtml]
@( Html.Syncfusion().Grid<Order>("UnBoundColumn_Grid", "GridModel",
column =>
{
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.CustomerID).HeaderText("Customer ID");
column.Add(p => p.ShipCountry).HeaderText("Ship
Country");
column.Add(p => p.ShipName).HeaderText("Ship Name");
column.Add(p =>
p.Freight).HeaderText("Freight").Format("{Freight:c}");
column.Add("Delete").HeaderText("Delete
Record").Format("<a class=\"TemplateCell\"
href=\"DeleteRecord?id={OrderID}\">Delete</a>");
}))
5. Create a GridPropertiesModel in the Index method. Assign grid properties in this model
and pass the model from controller to view using the ViewData class as given below.
6. Create a Delete action method which is used to delete the record from the database. This is
shown int he following code sample.
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult DeleteRecord(int id)
{
NorthwindDataContext context = new
NorthwindDataContext();
Order order = (Order)context.Orders.Single(p =>
p.OrderID == id);
context.Orders.DeleteOnSubmit(order);
context.SubmitChanges();
return RedirectToAction("Index");
}
4.2.5.1 Properties
Table 3: Property Table
4.2.5.2 Methods
Table 4: Methods Table
Sample Link
1. Through GridBuilder
2. Through GridPropertiesModel
The steps to configure the data binding support for drop-down column features using
GridBuilder are:
1. Create a model in the application. Refer to How to>Adding a Model to the Application and
Editing>EditableOrder Class.
2. Create a strongly typed view. Refer to How to>Strongly Typed View.
3. In the view, use the Model property in the Datasource() to bind the data source.
4. Enable editing using the Editing method and configure the editing properties such as
AllowNew, AllowEdit, and AllowDelete.
5. Essential Grid allows adding new records through grid toolbar items. Refer to Concepts and
Features > Editing.
6. Specify the primary property which uniquely identifies the grid record. Specify the
GridEditing mode using the EditMode() method. Refer to Concepts and Features >
Editing.
View [ASPX]
<%=Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model)
.Caption("Orders")
.Column(column =>
{
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.EmployeeID).HeaderText("Employee ID");
column.Add(p => p.CustomerID).HeaderText("Customer ID")
.CellEditType(CellEditType.DropdownEdit)
.DropDownDataSource((System.Collections.IEnumerable)
ViewData["DropDownSource"]);
column.Add(p => p.Verified).HeaderText("Verified");
column.Add(p => p.ShipRegion).HeaderText("Ship Region");
column.Add(p => p.Freight).HeaderText("Freight");
})
.EnablePaging()
.EnableSorting()
.EnableGrouping()
%>
View [cshtml]
@{ Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model)
.Caption("Orders")
.Column(column =>
{
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.EmployeeID).HeaderText("Employee ID");
column.Add(p => p.CustomerID).HeaderText("Customer ID")
.CellEditType(CellEditType.DropdownEdit)
.DropDownDataSource((System.Collections.IEnumerable)
ViewData["DropDownSource"]);
column.Add(p => p.Verified).HeaderText("Verified");
column.Add(p => p.ShipRegion).HeaderText("Ship Region");
column.Add(p => p.Freight).HeaderText("Freight");
})
.EnablePaging()
.EnableSorting()
.EnableGrouping()
.Render();
}
Controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddOrder(EditableOrder ord)
{
//Repository action method Add is used for inserting records into
the data source.
OrderRepository.Add(ord);
//After adding the record into database, refresh the grid.
var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult OrderSave(EditableOrder ord)
{
//Repository action method Update is used to update the
records into the data source.
OrderRepository.Update(ord);
10. In the controller, create a method to delete the records from the database as displayed
below. In this example, the repository action Delete() will delete the record from the data
source.
Controller
/// <summary>
/// Used for deleting the records from the data source and
refreshing the grid.
/// </summary>
/// <param name="OrderID">Primary key values.</param>
/// <returns>HtmlActionResult returns the data displayed on the
grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult DeleteOrder(int OrderID)
{
// Repository action Delete() deletes the given primary
value record from the data source.
OrderRepository.Delete(OrderID);
Figure 22: Grid with toolbar options for Editing, Inserting, and Deleting records
12. Edit any row. The grid will appear as shown below.
Figure 23: Data binding support for the CustomerID column in the grid
View [ASPX]
<%=Html.Syncfusion().Grid<EditableOrder>("Orders_Grid","GridModel",
column =>
{
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.EmployeeID).HeaderText("Employee ID");
column.Add(p => p.CustomerID).HeaderText("Customer ID")
.CellEditType(CellEditType.DropdownEdit)
.DropDownDataSource((System.Collections.IEnumerable)
ViewData["DropDownSource"]);
column.Add(p => p.Verified).HeaderText("Verified");
column.Add(p => p.ShipRegion).HeaderText("Ship Region");
column.Add(p => p.Freight).HeaderText("Freight");
})
%>
View [cshtml]
@( Html.Syncfusion().Grid<EditableOrder>("Orders_Grid","GridModel",
column =>
{
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.EmployeeID).HeaderText("Employee ID");
column.Add(p => p.CustomerID).HeaderText("Customer ID")
.CellEditType(CellEditType.DropdownEdit)
.DropDownDataSource((System.Collections.IEnumerable)
ViewData["DropDownSource"]);
column.Add(p => p.Verified).HeaderText("Verified");
column.Add(p => p.ShipRegion).HeaderText("Ship Region");
column.Add(p => p.Freight).HeaderText("Freight");
})
)
4. Create a GridPropertiesModel in the Index action and assign the grid properties in
the model.
Controller
ViewData["DropDownSource"] = DropDown;
ViewData["GridModel"] = model; // Pass the model from the
controller to the view using ViewData.
Controller
Controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddOrder(EditableOrder ord)
{
//Repository action method Add is used for inserting records
into the data source.
OrderRepository.Add(ord);
12. In the controller, create a method to save changes, as shown in the following code.
In this example, the repository method Update() is used to update records in the
data source.
Controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult OrderSave(EditableOrder ord)
{
//Repository action method Update used to update the records
into the data source.
OrderRepository.Update(ord);
//After saving the records into the data source, refresh the
grid.
var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}
13. In the controller, create a method to delete the records from the database as
displayed below.
In this example, the repository action Delete() will delete the record from the data source.
Controller
/// <summary>
/// Used to delete records from the data source and refresh the grid.
/// </summary>
/// <param name="OrderID">Primary key values.</param>
/// <returns>HtmlActionResult returns the data displayed in the
grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult DeleteOrder(int OrderID)
{
// Repository action Delete() deletes the given primary value record
from the data source.
OrderRepository.Delete(OrderID);
// After deleting, refresh the grid.
var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}
14. Run the application. The grid will appear as shown in the following screenshot.
Figure 24: Grid with Toolbar Options for Editing, Inserting, and Deleting Records
15. Edit any row. The grid will appear as shown below.
Figure 25: Data binding support for CustomerID column in the grid
1. Through GridBuilder
2. Through GridPropertiesModel
The steps to configure the data binding support for drop-down column features using
GridBuilder are:
1. Create a model in the application. Refer to How to>Adding a Model to the Application
and Editing>EditableOrder Class.
2. Create a strongly typed view. Refer to How to>Strongly Typed View.
3. In the view, use the Model property in the Datasource() to bind the data source.
4. Enable editing by using the Editing method and configure the editing properties such
as AllowNew, AllowEdit, and AllowDelete.
5. Essenital Grid allows adding new records through grid toolbar items. Refer to
Concepts and Features>Editing.
6. Specify the primary property which uniquely identifies the grid record. Specify the
GridEditing mode using the EditMode() method. Refer to Concepts and
Features>Editing.
View [ASPX]
<%=Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model)
.Caption("Orders")
.Column(column =>
{
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.EmployeeID).HeaderText("Employee ID");
column.Add(p => p.CustomerID).HeaderText("Customer ID")
.CellEditType(CellEditType.DropdownEdit)
.DropDownDataSource(System.Collections.IEnumerable)ViewData["DropDownSo
urce"], "Name", "StudentID");
column.Add(p => p.Verified).HeaderText("Verified");
column.Add(p => p.ShipRegion).HeaderText("Ship Region");
column.Add(p => p.Freight).HeaderText("Freight");
})
.EnablePaging()
.EnableSorting()
.EnableGrouping()
%>
View [ASPX]
<%=Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model)
.Caption("Orders")
.Column(column =>
{
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.EmployeeID).HeaderText("Employee ID");
column.Add(p => p.CustomerID).HeaderText("Customer ID")
.CellEditType(CellEditType.DropdownEdit)
.DropDownDataSource(System.Collections.IEnumerable)ViewData["DropDownSo
urce"], "Name", "StudentID");
column.Add(p => p.Verified).HeaderText("Verified");
Controller
8. In the controller, create a method to add new records to the grid as shown in the
following code. In this example, the repository method Add() is being created to
insert records in the database. Refer to the repository action method given below.
Controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddOrder(EditableOrder ord)
{
//Repository action method Add is used for inserting records into
the data source.
OrderRepository.Add(ord);
//After adding the record into the database, refresh the grid.
var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}
9. In the controller, create a method to save changes as shown in the following code
sample. In this example, the repository method Update() is used to update records to
the data source.
Controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult OrderSave(EditableOrder ord)
{
//Repository action method Update is used to update the
records into the data source.
OrderRepository.Update(ord);
10. In the controller, create a method to delete the records from the database as
displayed below. In this example, the repository action Delete() will delete the record
from the data source.
Controller
/// <summary>
/// Used for deleting the records from the data source and
refreshing the grid.
/// </summary>
/// <param name="OrderID">Primary key values.</param>
/// <returns>HtmlActionResult returns the data displayed on the
grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult DeleteOrder(int OrderID)
{
11. Run the application. The grid will appear as shown below.
Figure 26: Grid with Toolbar Options for Editing, Inserting, and Deleting Records
12. Edit any row. The grid will appear as shown below.
Figure 27: Data binding support for CustomerID column in the grid
View [ASPX]
<%=Html.Syncfusion().Grid<EditableOrder>("Orders_Grid","GridModel",
column =>
{
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.EmployeeID).HeaderText("Employee ID");
column.Add(p => p.CustomerID).HeaderText("Customer ID")
.CellEditType(CellEditType.DropdownEdit)
.DropDownDataSource(System.Collections.IEnumerable)ViewData["DropDownSo
urce"], "Name", "StudentID");
column.Add(p => p.Verified).HeaderText("Verified");
column.Add(p => p.ShipRegion).HeaderText("Ship Region");
column.Add(p => p.Freight).HeaderText("Freight");
})
%>
View [cshtml]
@( Html.Syncfusion().Grid<EditableOrder>("Orders_Grid","GridModel",
column =>
{
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.EmployeeID).HeaderText("Employee ID");
column.Add(p => p.CustomerID).HeaderText("Customer ID")
.CellEditType(CellEditType.DropdownEdit)
.DropDownDataSource(System.Collections.IEnumerable)ViewData["DropDownSo
urce"], "Name", "StudentID");
column.Add(p => p.Verified).HeaderText("Verified");
column.Add(p => p.ShipRegion).HeaderText("Ship Region");
column.Add(p => p.Freight).HeaderText("Freight");
})
)
4. Create a GridPropertiesModel in the Index action and assign the grid properties in
the model.
Controller
Controller
Controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddOrder(EditableOrder ord)
{
//Repository action method Add is used for inserting records
into the data source.
OrderRepository.Add(ord);
12. In the controller, create a method to save changes, as shown in the following code.
In this example, the repository method Update() is used to update records in the
data source.
Controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult OrderSave(EditableOrder ord)
{
//Repository action method Update is used to update the
records into the data source.
OrderRepository.Update(ord);
13. In the controller, create a method to delete the records from the database as
displayed below.
In this example, the repository action Delete() will delete the record from the data source.
Controller
/// <summary>
/// Used to delete records from the data source and refresh the grid.
/// </summary>
/// <param name="OrderID">Primary key values.</param>
/// <returns>HtmlActionResult returns the data displayed in the
grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult DeleteOrder(int OrderID)
{
// Repository action Delete() deletes the given primary value record
from the data source.
OrderRepository.Delete(OrderID);
// After deleting, refresh the grid.
var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}
14. Run the application. The grid will appear as shown in the following screenshot.
Figure 28: Grid with Toolbar Options for Editing, Inserting, and Deleting Records
15. Edit any row. The grid will appear as shown below.
Figure 29: Data binding support for CustomerID column in the grid
1. Through GridBuilder
2. Through GridPropertiesModel
1. Create a model in the application. Refer to How to>Adding a Model to the Application
and Editing>EditableOrder Class.
2. Create a strongly typed view. Refer to How to>Strongly Typed View.
3. In the view, use the Model property in the Datasource() to bind the data source.
4. Enable editing using the Editing method and configure the editing properties such as
AllowNew, AllowEdit, and AllowDelete.
5. Essenital Grid allows adding new records through grid toolbar items. Refer to
Concepts and Features>Editing.
6. Specify the primary property which uniquely identifies the grid record. Specify the
GridEditing mode using the EditMode() method. Refer to Concepts and
Features>Editing.
View [ASPX]
<%=Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource((IEnumerable<DataSource.Models.EditableOrder>)ViewDa
ta["data"])
.Caption("Orders")
.ActionMode(ActionMode.JSON)
.Column(column =>
{
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.EmployeeID).HeaderText("Employee ID");
column.Add(p => p.CustomerID).HeaderText("Customer ID")
.CellEditType(CellEditType.DropdownEdit)
.DropDownDataSource("getDropDownDetails");
column.Add(p => p.Verified).HeaderText("Verified");
column.Add(p => p.ShipRegion).HeaderText("Ship Region");
column.Add(p => p.Freight).HeaderText("Freight");
})
.EnablePaging()
.EnableSorting()
.EnableGrouping()
%>
View [cshtml]
@{ Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource((IEnumerable<DataSource.Models.EditableOrder>)ViewDa
ta["data"])
.Caption("Orders")
.ActionMode(ActionMode.JSON)
.Column(column =>
{
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.EmployeeID).HeaderText("Employee ID");
column.Add(p => p.CustomerID).HeaderText("Customer ID")
.CellEditType(CellEditType.DropdownEdit)
.DropDownDataSource("getDropDownDetails");
column.Add(p => p.Verified).HeaderText("Verified");
column.Add(p => p.ShipRegion).HeaderText("Ship Region");
column.Add(p => p.Freight).HeaderText("Freight");
})
.EnablePaging()
.EnableSorting()
.EnableGrouping()
.Render();
}
Controller
public ActionResult Index()
{
ViewData["data"] = OrderRepository.GetAllRecords();
return View();
}
8. In order to work with editing actions, create a Post method for the Index actions
and bind the data source to the grid as shown in the following code.
Controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = OrderRepository.GetAllRecords();
return data.GridJSONActions<EditableOrder>();
}
9. In the controller, create the method for the action name that has been specified in the
view to get the details of the drop-down list for that column.
Controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult getDropDownDetails()
{
var s = DropDown;
return Json(s, JsonRequestBehavior.AllowGet);
}
10. In the controller, create a method to add new records to the grid. In this example, the
repository method Add() is being created to insert records in the database. Refer to
the repository action method shown below.
Controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddOrder(EditableOrder ord)
{
//Repository action method Add is used to insert records into data
source.
OrderRepository.Add(ord);
//After adding the record into database, refresh the grid.
var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}
11. In the controller, create a method to save changes. In this example, the repository
method Update() is used to update records to the data source.
Controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult OrderSave(EditableOrder ord)
{
//Repository action method Update is used to update the
records into the data source.
OrderRepository.Update(ord);
12. In the controller, create a method to delete the records from the database as
displayed below. In this example, the repository action Delete() will delete the record
from the data source.
Controller
/// <summary>
/// Used for deleting the records from the data source and
refreshing the grid.
/// </summary>
/// <param name="OrderID">Primary key values.</param>
/// <returns>HtmlActionResult returns the data displayed on the
grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult DeleteOrder(int OrderID)
{
// Repository action Delete() deletes the given primary
value record from the data source.
OrderRepository.Delete(OrderID);
13. Run the application. The grid will appear as shown below.
Figure 30: Grid with Toolbar Options for Editing, Inserting, and Deleting Records
14. Edit any row. The grid will appear as shown below.
Figure 31: Data binding support for CustomerID column in the grid
The steps to configure the data binding support for drop-down column features using the
GridPropertiesModel are:
View [ASPX]
<%=Html.Syncfusion().Grid<EditableOrder>("Orders_Grid","GridModel",
column =>
{
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.EmployeeID).HeaderText("Employee ID");
column.Add(p => p.CustomerID).HeaderText("Customer ID")
.CellEditType(CellEditType.DropdownEdit)
.DropDownDataSource("getDropDownDetails");
column.Add(p => p.Verified).HeaderText("Verified");
column.Add(p => p.ShipRegion).HeaderText("Ship Region");
column.Add(p => p.Freight).HeaderText("Freight");
})
%>
View [ASPX]
<%=Html.Syncfusion().Grid<EditableOrder>("Orders_Grid","GridModel",
column =>
{
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.EmployeeID).HeaderText("Employee ID");
column.Add(p => p.CustomerID).HeaderText("Customer ID")
.CellEditType(CellEditType.DropdownEdit)
.DropDownDataSource("getDropDownDetails");
column.Add(p => p.Verified).HeaderText("Verified");
column.Add(p => p.ShipRegion).HeaderText("Ship Region");
column.Add(p => p.Freight).HeaderText("Freight");
})
%>
4. Create a GridPropertiesModel in the Index action and assign the grid properties in
the model.
Controller
ActionMode = ActionMode.JSON,
Caption = "Orders",
AllowPaging = true,
AllowSorting = true,
AllowGrouping=true,
AutoFormat=Skins.Sandune
};
ViewData["GridModel"] = model; // Pass the model from
controller to view using ViewData.
5. In order to work with editing actions, create a Post method for Index actions
and bind the data source to the grid as shown in the following code.
Controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = OrderRepository.GetAllRecords();
return data.GridJSONActions<EditableOrder>();
}
6. In the controller, create the method for the action name that has been specified in
the view to get the details of the drop-down list.
Controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult getDropDownDetails()
{
var s = DropDown;
return Json(s, JsonRequestBehavior.AllowGet);
}
Controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddOrder(EditableOrder ord)
{
//The repository action method Add is used to insert records
into the data source.
OrderRepository.Add(ord);
13. In the controller, create a method to save changes, as shown in the following code.
In this example, the repository method Update() is used to update records in the
data source.
Controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult OrderSave(EditableOrder ord)
{
//Repository action method Update is used to update the
records into the data source.
OrderRepository.Update(ord);
14. In the controller, create a method to delete the records from the database as
displayed below. In this example, the repository action Delete() will delete the record
from the data source.
Controller
/// <summary>
/// Used to delete records from the data source and refresh the grid.
/// </summary>
/// <param name="OrderID">Primary key values.</param>
/// <returns>HtmlActionResult returns the data displayed in the
grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult DeleteOrder(int OrderID)
{
// Repository action Delete() deletes the given primary value record
from the data source.
OrderRepository.Delete(OrderID);
// After deleting, refresh the grid.
var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}
15. Run the application. The grid will appear as shown in the following screenshot:
Figure 32: Grid with Toolbar Options for Editing, Inserting, and Deleting Records
16. Edit any row. The grid will appear as shown below.
Figure 33: Data binding support for CustomerID column in the grid
1. Through GridBuilder
2. Through GridPropertiesModel
1. Create a model in the application. Refer to How to>Adding a Model to the Application
and Editing>EditableOrder Class.
2. Create a strongly typed view. Refer to How to>Strongly Typed View.
3. In the view, use the Model property in the Datasource() to bind the data source.
4. Enable editing by using the Editing method and configure the editing properties such
as AllowNew, AllowEdit, and AllowDelete.
5. Essenital Grid allows adding new records through grid toolbar items. Refer to
Concepts and Features>Editing.
6. Specify the primary property which uniquely identifies the grid record. Specify the
GridEditing mode using the EditMode() method. Refer to Concepts and
Features>Editing.
View [ASPX]
<%=Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource((IEnumerable<DataSource.Models.EditableOrder>)ViewDa
ta["data"])
.Caption("Orders")
.ActionMode(ActionMode.JSON)
.Column(column =>
{
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.EmployeeID).HeaderText("Employee ID");
column.Add(p => p.CustomerID).HeaderText("Customer ID")
.CellEditType(CellEditType.DropdownEdit)
.DropDownDataSource("getDropDownDetails","Name","StudentID");
column.Add(p => p.Verified).HeaderText("Verified");
column.Add(p => p.ShipRegion).HeaderText("Ship Region");
column.Add(p => p.Freight).HeaderText("Freight");
})
.EnablePaging()
.EnableSorting()
.EnableGrouping()
%>
View [cshtml]
@{ Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource((IEnumerable<DataSource.Models.EditableOrder>)ViewDa
ta["data"])
.Caption("Orders")
.ActionMode(ActionMode.JSON)
.Column(column =>
{
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.EmployeeID).HeaderText("Employee ID");
column.Add(p => p.CustomerID).HeaderText("Customer ID")
.CellEditType(CellEditType.DropdownEdit)
.DropDownDataSource("getDropDownDetails","Name","StudentID");
column.Add(p => p.Verified).HeaderText("Verified");
column.Add(p => p.ShipRegion).HeaderText("Ship Region");
column.Add(p => p.Freight).HeaderText("Freight");
})
.EnablePaging()
.EnableSorting()
.EnableGrouping()
.Render();
}
Controller
public ActionResult Index()
{
ViewData["data"] = OrderRepository.GetAllRecords();
return View();
}
8. In order to work with editing actions, create a Post method for Index actions and bind
the data source to the grid as shown in the following code.
Controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = OrderRepository.GetAllRecords();
return data.GridJSONActions<EditableOrder>();
}
9. In the controller, create the method for the action name that has been specified in the
view to get the details of the drop-down list.
Controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult getDropDownDetails()
{
var s = DropDown;
return Json(s, JsonRequestBehavior.AllowGet);
}
10. In the controller, create a method to add new records to the grid. In this example, the
repository method Add() is being created to insert records in the database. Refer to
the repository action method given below.
Controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddOrder(EditableOrder ord)
{
//Repository action method Add is used to insert records into the
data source.
OrderRepository.Add(ord);
//After adding the record into the database, refresh the grid.
var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}
11. In the controller, create a method to save changes. In this example, the repository
method Update() is used to update records to the data source.
Controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult OrderSave(EditableOrder ord)
{
//Repository action method Update is used to update the
records into the data source.
OrderRepository.Update(ord);
12. In the controller, create a method to delete the records from the database as
displayed below. In this example, the repository action Delete() will delete the record
from the data source.
Controller
/// <summary>
/// Used for deleting the records from the data source and
refreshing the grid.
/// </summary>
/// <param name="OrderID">Primary key values.</param>
/// <returns>HtmlActionResult returns the data displayed on the
grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult DeleteOrder(int OrderID)
{
// Repository action Delete() deletes the given primary
13. Run the application. The grid will appear as shown below.
Figure 34: Grid with Toolbar Options for Editing, Inserting, and Deleting Records
14. Edit any row. The grid will appear as shown below.
Figure 35: Data binding support for CustomerID column in the grid
View [ASPX]
<%=Html.Syncfusion().Grid<EditableOrder>("Orders_Grid","GridModel",
column =>
{
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.EmployeeID).HeaderText("Employee ID");
column.Add(p => p.CustomerID).HeaderText("Customer ID")
.CellEditType(CellEditType.DropdownEdit)
.DropDownDataSource("getDropDownDetails","Name","StudentID");
column.Add(p => p.Verified).HeaderText("Verified");
column.Add(p => p.ShipRegion).HeaderText("Ship Region");
column.Add(p => p.Freight).HeaderText("Freight");
})
%>
View [cshtml]
@( Html.Syncfusion().Grid<EditableOrder>("Orders_Grid","GridModel",
column =>
{
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.EmployeeID).HeaderText("Employee ID");
column.Add(p => p.CustomerID).HeaderText("Customer ID")
.CellEditType(CellEditType.DropdownEdit)
.DropDownDataSource("getDropDownDetails","Name","StudentID");
column.Add(p => p.Verified).HeaderText("Verified");
column.Add(p => p.ShipRegion).HeaderText("Ship Region");
column.Add(p => p.Freight).HeaderText("Freight");
})
)
4. Create a GridPropertiesModel in the Index action and assign the grid properties in
the model.
Controller
5. In order to work with editing actions, create a Post method for Index actions
and bind the data source to the grid as shown in the following code.
Controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = OrderRepository.GetAllRecords();
return data.GridJSONActions<EditableOrder>();
}
6. In the controller, create the method for the action name that has been specified in
the view to get the details of the drop-down list.
Controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult getDropDownDetails()
{
var s = DropDown;
return Json(s, JsonRequestBehavior.AllowGet);
}
Controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddOrder(EditableOrder ord)
{
//Repository action method Add is used to insert records into
the data source.
OrderRepository.Add(ord);
13. In the controller, create a method to save changes, as shown in the following code.
In this example, the repository method Update() is used to update records in the
data source.
Controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult OrderSave(EditableOrder ord)
{
14. In the controller, create a method to delete the records from the database as
displayed below. In this example, the repository action Delete() will delete the record
from the data source.
Controller
/// <summary>
/// Used to delete records from the data source and refresh the grid.
/// </summary>
/// <param name="OrderID">Primary key values.</param>
/// <returns>HtmlActionResult returns the data displayed in the
grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult DeleteOrder(int OrderID)
{
// Repository action Delete() deletes the given primary value record
from the data source.
OrderRepository.Delete(OrderID);
// After deleting, refresh the grid.
var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}
15. Run the application. The grid will appear as shown in the following screenshot.
Figure 36: Grid with Toolbar Options for Editing, Inserting, and Deleting Records
16. Edit any row. The grid will appear as shown below.
Figure 37: Data binding support for CustomerID column in the grid
1. Through GridBuilder
2. Through GridPropertiesModel
1. Create a model in the application. Refer to How to>Adding a Model to the Application
and Editing>EditableOrder Class.
2. Create a strongly typed view. Refer to How to>Strongly Typed View.
3. In the view, use the Model property in the Datasource() to bind the data source.
4. Enable editing by using the Editing method and configure the editing properties such
as AllowNew, AllowEdit, and AllowDelete.
5. Essenital Grid allows adding new records through grid toolbar items. Refer to
Concepts and Features>Editing.
6. Specify the primary property which uniquely identifies the grid record. Specify the
GridEditing mode using the EditMode() method. Refer to Concepts and
Features>Editing.
View [ASPX]
<%=Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model)
.Caption("Orders")
.Column(column =>
{
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.EmployeeID).HeaderText("Employee ID");
column.Add(p => p.CustomerID).HeaderText("Customer ID")
.CellEditType(CellEditType.DropdownEdit)
.DropDownDataSource((Array)ViewData["DropDownSource"]);
column.Add(p => p.Verified).HeaderText("Verified");
column.Add(p => p.ShipRegion).HeaderText("Ship Region");
column.Add(p => p.Freight).HeaderText("Freight");
})
.EnablePaging()
.EnableSorting()
.EnableGrouping()
%>
View [cshtml]
@{ Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model)
.Caption("Orders")
.Column(column =>
{
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.EmployeeID).HeaderText("Employee ID");
column.Add(p => p.CustomerID).HeaderText("Customer ID")
.CellEditType(CellEditType.DropdownEdit)
.DropDownDataSource((Array)ViewData["DropDownSource"]);
column.Add(p => p.Verified).HeaderText("Verified");
column.Add(p => p.ShipRegion).HeaderText("Ship Region");
column.Add(p => p.Freight).HeaderText("Freight");
})
.EnablePaging()
.EnableSorting()
.EnableGrouping()
.Render();
}
Controller
8. In the controller, create a method to add new records to the grid. In this example, the
repository method Add() is being created to insert records in the database. Refer to
the repository action method given below.
Controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddOrder(EditableOrder ord)
{
//Repository action method Add is used to insert records into the
data source.
OrderRepository.Add(ord);
//After adding the record into the database, refresh the grid.
var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}
9. In the controller, create a method to save changes. In this example, the repository
method Update() is used to update records to the data source.
Controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult OrderSave(EditableOrder ord)
{
//Repository action method Update used for perform update
the records into datasource
OrderRepository.Update(ord);
10. In the controller, create a method to delete the records from the database as
displayed below. In this example, the repository action Delete() will delete the record
from the data source.
Controller
/// <summary>
/// Used for deleting the records from the data source and
refreshing the grid.
/// </summary>
/// <param name="OrderID">Primary key values.</param>
/// <returns>HtmlActionResult returns the data displayed on the
grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult DeleteOrder(int OrderID)
{
// Repository action Delete() deletes the given primary
value record from the data source.
OrderRepository.Delete(OrderID);
11. Run the application. The grid will appear as shown below.
Figure 38: Grid with Toolbar Options for Editing, Inserting, and Deleting Records
12. Edit any row. The grid will appear as shown below.
Figure 39: Data binding support for CustomerID column in the grid
View [ASPX]
<%=Html.Syncfusion().Grid<EditableOrder>("Orders_Grid","GridModel",
column =>
{
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.EmployeeID).HeaderText("Employee ID");
column.Add(p => p.CustomerID).HeaderText("Customer ID")
.CellEditType(CellEditType.DropdownEdit)
.DropDownDataSource((Array)ViewData["DropDownSource"]);
column.Add(p => p.Verified).HeaderText("Verified");
column.Add(p => p.ShipRegion).HeaderText("Ship Region");
column.Add(p => p.Freight).HeaderText("Freight");
})
%>
View [cshtml]
@( Html.Syncfusion().Grid<EditableOrder>("Orders_Grid","GridModel",
column =>
{
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.EmployeeID).HeaderText("Employee ID");
column.Add(p => p.CustomerID).HeaderText("Customer ID")
.CellEditType(CellEditType.DropdownEdit)
.DropDownDataSource((Array)ViewData["DropDownSource"]);
column.Add(p => p.Verified).HeaderText("Verified");
column.Add(p => p.ShipRegion).HeaderText("Ship Region");
column.Add(p => p.Freight).HeaderText("Freight");
})
)
4. Create a GridPropertiesModel in the Index action and assign the grid properties in
the model.
Controller
Controller
Controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddOrder(EditableOrder ord)
{
//Repository action method Add is used insert records into the
data source.
OrderRepository.Add(ord);
12. In the controller, create a method to save changes. In this example, the repository
method Update() is used to update records in the data source.
Controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult OrderSave(EditableOrder ord)
{
//Repository action method Update is used to update the
records into the data source.
OrderRepository.Update(ord);
13. In the controller, create a method to delete the records from the database as
displayed below. In this example, the repository action Delete() will delete the record
from the data source.
Controller
/// <summary>
/// Used to delete records from the data source and refresh the grid.
/// </summary>
/// <param name="OrderID">Primary key values.</param>
/// <returns>HtmlActionResult returns the data displayed in the
grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult DeleteOrder(int OrderID)
{
// Repository action Delete() deletes the given primary value record
from the data source.
OrderRepository.Delete(OrderID);
// After deleting, refresh the grid.
var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}
14. Run the application. The grid will appear as shown in the following screenshot.
Figure 40: Grid with Toolbar Options for Editing, Inserting, and Deleting Records
15. Edit any row. The grid will appear as shown below
Figure 41: Data binding support for CustomerID column in the grid
Sample Link
To view the samples, follow the steps below:
1. Open the Grid sample browser from the dashboard (refer to the Samples and Location
chapter).
2. Navigate to Grid.MVC > Editing > Server Mode/JSON Mode
<%=Html.Syncfusion().Grid<Product>("ProductGrid")
.Datasource(Model)
.Caption("Product Details")
%>
View [cshtml]
@{ Html.Syncfusion().Grid<Product>("ProductGrid")
.Datasource(Model)
.Caption("Product Details")
}
4. Set its data source and render the view.
Controller
/// <summary>
/// Used to bind the grid.
/// </summary>
/// <returns>View page; it displays the grid.</returns>
public ActionResult Index()
{
var data = new NorthwindDataContext().Products.Take(15);
return View(data);
}
1. Create a model in the application (refer to How to>Adding a Model to the Application)
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. In the view you can use its Model property in Datasource in order to bind the data source
alone. Don’t specify any visible column collections to the grid. The grid automatically
populates the columns from its model.
View [ASPX]
<%=Html.Syncfusion().Grid<Product>("ProductGrid",(GridPropertiesModel)V
iewData["GridModel"]) %>
View [cshtml]
@(
Html.Syncfusion().Grid<Product>("ProductGrid",(GridPropertiesModel)View
Data["GridModel"]))
4. Create a GridPropertiesModel in the Index method. Assign grid properties in this model
and pass the model from controller to view using the ViewData class as given below.
Controller
/// <summary>
/// Used for display the grid.
/// </summary>
/// <returns> View page which displays the grid.</returns>
public ActionResult Index()
{
GridPropertiesModel<Product> model = new
GridPropertiesModel<Product>()
{
DataSource = new
NorthwindDataContext().Products.Take(15),
Caption = "Product Grid"
};
ViewData["GridModel"]=model;
return View();
}
Properties
Methods
You can work with the custom binding feature through two ways:
GridBuilder
GridPropertiesModel
The steps to work with the custom binding feature through GridBuilder are as follows:
1. Create a model in the application. Refer to How to>Adding Model to the Application.
2. Create a strongly typed view. Refer to How to>Strongly Typed View.
3. In the view, use the Model property in the Datasource() to bind the data source. In this
example, sorting, paging, and filtering are enabled.
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("OrdersGrid")
.Datasource(Model)
.Caption("Orders")
.Column(column =>
{
column.Add(c => c.OrderID).HeaderText("Order ID");
column.Add(c => c.OrderDate).HeaderText("Order
Date").Format("{0:dd/MM/yyyy}");
View [cshtml]
@{ Html.Syncfusion().Grid<Order>("OrdersGrid")
.Datasource(Model)
.Caption("Orders")
.Column(column =>
{
column.Add(c => c.OrderID).HeaderText("Order ID");
column.Add(c => c.OrderDate).HeaderText("Order
Date").Format("{0:dd/MM/yyyy}");
column.Add(c => c.CustomerID).HeaderText("Customer ID");
column.Add(c => c.ShipCountry).HeaderText("Ship Country");
column.Add(c => c.ShipCity).HeaderText("Ship City");
column.Add(c =>
c.Freight).HeaderText("Frieght").Format("{Freight:#,#}");
})
.EnablePaging()
.EnableSorting()
.EnableFiltering().Render();
}
<%=Html.Syncfusion().Grid<Order>("OrdersGrid")
.Datasource(Model)
.Caption("Orders")
……………
……………
.EnableOnDemand()
……………
……………
%>
View [cshtml]
@{ Html.Syncfusion().Grid<Order>("OrdersGrid")
.Datasource(Model)
.Caption("Orders")
……………
……………
.EnableOnDemand()
……………
……………
.Render();
}
5. Set the TotalRecordCount by specifying the total record count the grid should display. This
field is required to display the grid pager accurately.
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("OrdersGrid")
.Datasource(Model)
.Caption("Orders")
……………
……………
.TotalRecordCount(200)
……………
……………
%>
View [cshtml]
@{ Html.Syncfusion().Grid<Order>("OrdersGrid")
.Datasource(Model)
.Caption("Orders")
……………
……………
.TotalRecordCount(200)
……………
……………
.Render();
}
6. In the grid Post actions, check the request type. If the action type is paging, sorting, or
filtering the request, then process the data and bind the data to the action result. Bind the
GridActionResult with the totalrecount which is used to render the pages in all the
custom binding actions.
Controller
/// <summary>
/// <summary>
/// Utility method for performing data processing.
/// </summary>
/// <param name="args">Paging params.</param>
/// <returns>IQueryable data source.</returns>
private IEnumerable GetData(PagingParams args)
{
int pagesize = args.PageSize == 0 ? 12 :
Convert.ToInt32(args.PageSize);
IEnumerable data = new
NorthwindDataContext().Orders.Take(200).ToList();
IQueryable ds = data.AsQueryable();
if (args.SortDescriptors[i].SortDirection ==
ListSortDirection.Ascending)
{
ds = ds.OrderBy(sortColumnName);
}
else if (args.SortDescriptors[i].SortDirection
== ListSortDirection.Descending)
{
ds = ds.OrderByDescending(sortColumnName);
}
}
else
{
if (args.SortDescriptors[i].SortDirection ==
ListSortDirection.Ascending)
{
ds = ds.ThenBy(sortColumnName);
}
else if (args.SortDescriptors[i].SortDirection
== ListSortDirection.Descending)
{
ds = ds.ThenByDescending(sortColumnName);
}
}
}
}
totalrecordCount = ds.Count();
if (totalrecordCount > 0)
data =
ds.Skip(Convert.ToInt32(args.StartIndex)).Take(pagesize);
else
data = ds;
return data;
}
7. Run the application. The grid will appear as displayed below.
The steps to work with the custom binding feature through GridPropertiesModel are as follows:
1. Create a model in the application. (Refer to How to>Adding a Model to the Application.)
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. Add the following code in the Index.aspx file to create the Grid control in the view.
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("Orders_Grid","GridModel",
column=> {
column.Add(c => c.OrderID).HeaderText("Order
ID");
column.Add(c => c.OrderDate).HeaderText("Order
Date").Format("{0:dddd, MMMM d, yyyy}");
column.Add(c =>
c.CustomerID).HeaderText("Customer ID");
column.Add(c => c.ShipCountry).HeaderText("Ship
Country");
column.Add(c => c.ShipCity).HeaderText("Ship
City");
column.Add(c =>
c.ShipPostalCode).HeaderText("Ship postal Code");
column.Add(c =>
c.Freight).HeaderText("Frieght").Format("{Freight:#,#}");
})%>
View [cshtml]
@( Html.Syncfusion().Grid<Order>("Orders_Grid","GridModel",
column=> {
column.Add(c => c.OrderID).HeaderText("Order
ID");
column.Add(c => c.OrderDate).HeaderText("Order
Date").Format("{0:dddd, MMMM d, yyyy}");
column.Add(c =>
c.CustomerID).HeaderText("Customer ID");
column.Add(c => c.ShipCountry).HeaderText("Ship
Country");
column.Add(c => c.ShipCity).HeaderText("Ship
City");
column.Add(c =>
c.ShipPostalCode).HeaderText("Ship postal Code");
column.Add(c =>
c.Freight).HeaderText("Frieght").Format("{Freight:#,#}");
}))
4. Create a GridPropertiesModel in the Index method and assign the grid properties in the
model. In this example, sorting, paging, and filtering are enabled.
Controller
};
EnableOnDemand=true,
};
6. Set the TotalRecordCount by specifying the total record count the grid should display. This
field is required to display the grid pager accurately.
Controller
7. In the grid Post actions, check the request type. If the action type is paging, sorting, or
filtering a request, then process the data and bind the data to the action result. Bind the
GridActionResult with the totalrecount which is used to render the pages in all the
custom binding actions.
/// <summary>
/// Grid actions for paging/sorting/grouping/filering/editing.
/// OnDemand mode enabled only for paging, sorting, and
filtering actions.
/// New FilterConditions property added in paging params which
holds the filter
/// conditions.
/// </summary>
/// <param name="args">Paging params.</param>
/// <returns>Action result.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = null;
RequestType currentRequest =
(RequestType)Convert.ToInt32(args.RequestType);
if (args.EnableOnDemand && (currentRequest ==
RequestType.Sorting || currentRequest == RequestType.Paging ||
currentRequest == RequestType.Filtering))
{
data = this.GetData(args);
}
else
{
data = new
NorthwindDataContext().Orders.Take(200).ToList();
}
return data.GridActions<Order>(totalrecordCount);
}
/// <summary>
/// Utility method for perform the data processing.
/// </summary>
/// <param name="args">Paging params.</param>
/// <returns>IQueryable data source.</returns>
private IEnumerable GetData(PagingParams args)
{
int pagesize = args.PageSize == 0 ? 12 :
Convert.ToInt32(args.PageSize);
IEnumerable data = new
NorthwindDataContext().Orders.Take(200).ToList();
IQueryable ds = data.AsQueryable();
if (args.SortDescriptors[i].SortDirection ==
ListSortDirection.Ascending)
{
ds = ds.OrderBy(sortColumnName);
}
else if (args.SortDescriptors[i].SortDirection
== ListSortDirection.Descending)
{
ds = ds.OrderByDescending(sortColumnName);
}
}
else
{
if (args.SortDescriptors[i].SortDirection ==
ListSortDirection.Ascending)
{
ds = ds.ThenBy(sortColumnName);
}
else if (args.SortDescriptors[i].SortDirection
== ListSortDirection.Descending)
{
ds = ds.ThenByDescending(sortColumnName);
}
}
}
}
totalrecordCount = ds.Count();
if (totalrecordCount > 0)
data =
ds.Skip(Convert.ToInt32(args.StartIndex)).Take(pagesize);
else
data = ds;
return data;
}
1. Open the Grid sample browser from the dashboard (refer to the Samples and Location
chapter).
2. Navigate to Grid.MVC > Data Binding > Custom Data Binding
.Caption("Orders")
.WebService("/Models/Orders.asmx/RenderOrders")
.Column(column =>
{
column.Add(p =>
p.OrderID).HeaderText("OrderID");
column.Add(p =>
p.EmployeeID).HeaderText("EmployeeID");
column.Add(p =>
p.ShipAddress).HeaderText("ShipAddress");
column.Add(p =>
p.ShipCountry).HeaderText("ShipCountry");
})
.EnablePaging().PageSettings(p =>
p.PageCount(5))
.EnableSorting()
.EnableGrouping().EnableFiltering()
.AutoFormat(Skins.Sandune)
.ToolBar(tools =>
{
tools.Add(GridToolBarItems.AddNew)
.Add(GridToolBarItems.Edit)
.Add(GridToolBarItems.Delete)
.Add(GridToolBarItems.Update)
.Add(GridToolBarItems.Cancel);
})
.Editing( edit=>{
edit.AllowEdit(true,
"/Models/Orders.asmx/OrderSave")
.AllowNew(true,
"/Models/Orders.asmx/AddOrder")
.AllowDelete(true,
"/Models/Orders.asmx/DeleteOrder")
.EditMode(GridEditMode.InlineForm)
.PrimaryKey(key => key.Add(p => p.OrderID));
})
%>
View [cshtml]
@{Html.Syncfusion().Grid<Order>("Grid1")
.Caption("Orders")
.WebService("/Models/Orders.asmx/RenderOrders")
.Column(column =>
{
column.Add(p =>
p.OrderID).HeaderText("OrderID");
column.Add(p =>
p.EmployeeID).HeaderText("EmployeeID");
column.Add(p =>
p.ShipAddress).HeaderText("ShipAddress");
column.Add(p =>
p.ShipCountry).HeaderText("ShipCountry");
})
.EnablePaging().PageSettings(p =>
p.PageCount(5))
.EnableSorting()
.EnableGrouping().EnableFiltering()
.AutoFormat(Skins.Sandune)
.ToolBar(tools =>
{
tools.Add(GridToolBarItems.AddNew)
.Add(GridToolBarItems.Edit)
.Add(GridToolBarItems.Delete)
.Add(GridToolBarItems.Update)
.Add(GridToolBarItems.Cancel);
})
.Editing( edit=>{
edit.AllowEdit(true,
"/Models/Orders.asmx/OrderSave")
.AllowNew(true,
"/Models/Orders.asmx/AddOrder")
.AllowDelete(true,
"/Models/Orders.asmx/DeleteOrder")
.EditMode(GridEditMode.InlineForm)
.PrimaryKey(key => key.Add(p => p.OrderID));
})
.Render();
}
6. Bind the grid to Web services using object data sources. The Web service method must
have a parameter webParams of type WebServiceParams which maintains the current
state of the grid for filtering, editing, sorting, paging, and grouping actions. Also, the Web
service method should return the GridWebService object.
8.
[WebMethod]
public GridWebService OrderSave(WebServiceParams webParams, Order
datasourceObj)
{
8. Create a WebMethod for adding records. The Web service method must have parameters
webParams of type WebServiceParams and datasourceObj of the particular data source
object type. The datasourceObj parameter contains the new record which has to be
added.
9. Create a WebMethod for adding records. The Web service method must have parameters
webParams of type WebServiceParams and KeyValue of the same type as the primary
column. The KeyValue parameter contains the particular record’s primary column value
which is used to delete that particular record.
10. Run the application. The grid will appear as shown in the following figure:
1. Create a model in the application (refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (refer to How to>Strongly Typed View).
3. Add the following code in the Index.aspx file to create the Grid control in the view.
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("Grid1", column=>
{
column.Add(p =>
p.OrderID).HeaderText("OrderID");
column.Add(p =>
p.EmployeeID).HeaderText("EmployeeID");
column.Add(p =>
p.ShipAddress).HeaderText("ShipAddress");
column.Add(p =>
p.ShipCountry).HeaderText("ShipCountry");
}));
%>
View [cshtml]
@( Html.Syncfusion().Grid<Order>("Grid1", column=>
{
column.Add(p => p.OrderID).HeaderText("OrderID");
column.Add(p => p.EmployeeID).HeaderText("EmployeeID");
column.Add(p => p.ShipAddress).HeaderText("ShipAddress");
column.Add(p => p.ShipCountry).HeaderText("ShipCountry");
})
)
4. Create a GridPropertiesModel in the Index method and assign the grid properties in the
model.
Controller
5. Enable editing by using the Editing property in the GridPropertiesModel, and configure
the editing properties such as AllowNew, AllowEdit, and AllowDelete as shown in the
following code sample:
Controller
6. Essential Grid allows adding new records through grid toolbar items. In this example, the
AddNew, Edit, Delete, Save, and Cancel buttons have been added as toolbar items as
shown in the following code sample:
Controller
// Configure the toolbar.
ToolbarSettings toolbar = new ToolbarSettings();
toolbar.Enable = true;
// Add the add new, edit, delete, save, and cancel buttons in the
toolbar.
toolbar.Items.Add(new ToolbarOptions() {
ItemType=GridToolBarItems.AddNew});
toolbar.Items.Add(new ToolbarOptions() { ItemType =
GridToolBarItems.Edit });
toolbar.Items.Add(new ToolbarOptions() { ItemType =
GridToolBarItems.Update });
toolbar.Items.Add(new ToolbarOptions() { ItemType =
GridToolBarItems.Delete });
toolbar.Items.Add(new ToolbarOptions() { ItemType =
GridToolBarItems.Cancel });
gridModel.ToolBar = toolbar;
ViewData["Grid1"] = gridModel;
return View();
7. Bind the grid to a Web service using object data sources. The Web service method must
have a parameter webParams of the type WebServiceParams which maintains the current
state of the grid for filtering, editing, sorting, paging, and grouping actions. Also, the Web
service method should return the GridWebService object.
9. Create a WebMethod for adding records. The Web service method must have the
parameters webParams of the type WebServiceParams and datasourceObj of the
particular data source object type. The datasourceObj parameter contains the new record
which has to be added.
10. Create a WebMethod for adding records as shown in the following code samples. The Web
service method must have the parameters webParams of type WebServiceParams and
KeyValue of the same type as the primary column. The KeyValue parameter contains the
particular record’s primary column value which is used to delete that particular record.
11. Run the application. The grid will appear as shown in the following figure:
Properties
Any other
Type of dependencies/s
Property Description Value it accepts
property ub-properties
associated
Gets or sets the
URL for binding
the grid to a
WebService string string NA
Web service
using object
data source.
Sample Link
To view the samples, follow the steps below:
1. Open the Grid sample browser from the dashboard (Refer to the Samples and Location
chapter).
2. Navigate to Grid.MVC > Data Binding > Web Service Binding
The dynamic data binding feature does not need any parameters to define the grid. This feature
will be useful to dynamically define the ModelType of the grid. According to the data source the
grid will render the columns internally.
<% =Html.Syncfusion().Grid<object>("Grid1")
.Datasource((IEnumerable)ViewData["data"])
.Caption("Dynamic DataSource")
.AutoFormat(Skins.Almond)
%>
View [cshtml]
@{ Html.Syncfusion().Grid<object>("Grid1")
.Datasource((IEnumerable)ViewData["data"])
.Caption(ViewData["datatype"].ToString())
.AutoFormat(Skins.Almond)
.Render();
}
4. Set its data source in the corresponding ViewData and render the view.
[Controller]
public ActionResult Index()
{
Caption = "Orders",
};
ViewData["GridModel"] = gridModel;
return View();
Methods
<% =Html.Syncfusion().Grid<object>("Grid1")
.Datasource((IEnumerable)ViewData["data"])
.Column(col=>{
col.Add("OrderId").UnBound(false);
col.Add("OrderDate").UnBound(false);
col.Add("CustomerID").UnBound(false);
col.Add("ShipDate").UnBound(false);
col.Add("ShipAddress").UnBound(false);
})
.Caption("Dynamic DataSource")
.AutoFormat(Skins.Almond)
%>
View [cshtml]
@{ Html.Syncfusion().Grid<object>("Grid1")
.Datasource((IEnumerable)ViewData["data"])
.Column(col=>{
col.Add("OrderId").UnBound(false);
col.Add("OrderDate").UnBound(false);
col.Add("CustomerID").UnBound(false);
col.Add("ShippedDate").UnBound(false);
col.Add("ShipAddress").UnBound(false);
})
.Caption(ViewData["datatype"].ToString())
.AutoFormat(Skins.Almond)
.Render();
}
5. Set its data source in corresponding ViewData and render the view.
[Controller]
public ActionResult Index()
return View();
col.Add("OrderId").UnBound(false);
col.Add("OrderDate").UnBound(false);
col.Add("CustomerID").UnBound(false);
col.Add("ShippedDate").UnBound(false);
col.Add("ShipAddress").UnBound(false);
} ) %>
View [cshtml]
@( Html.Syncfusion().Grid<object>("Grid1","GridModel", col => {
col.Add("OrderId").UnBound(false);
col.Add("OrderDate").UnBound(false);
col.Add("CustomerID").UnBound(false);
col.Add("ShippedDate").UnBound(false);
col.Add("ShipAddress").UnBound(false);
} ))
[Controller]
public ActionResult Index()
{
GridPropertiesModel<object> gridModel = new
GridPropertiesModel<object>()
{
DataSource = new NorthwindDataContext().Orders,
Caption = "Orders",
};
ViewData["GridModel"] = gridModel;
return View();
Sample Link
To view the samples, follow the steps below:
1. Open the Grid sample browser from the dashboard (Refer to the Samples and Location
chapter).
2. Navigate to Grid.MVC > Data Binding > Dynamic Data Binding Mode
Properties
Property Description Type of Value it Accepts Any Other
Property Dependencies/Sub-
Properties
Associated
DataSource Gets or sets the DataTable Any DataTable None
data source for the data.
Grid control.
Methods
Method Description Parameters Return Type
Datasource Used to set a data source to the DataTable data source IGridBuilder<T>
(DataTable) Grid control.
View [ASPX]
<%=Html.Syncfusion().Grid<System.Data.DataRow>("OrdersGrid")
.Datasource(Model)
.Column(col =>
{
col.Add("OrderID", false).HeaderText("Order ID");
col.Add("RequiredDate", false).HeaderText("Required
Date");
col.Add("Freight", false). HeaderText("Freight");
col.Add("ShipName", false).HeaderText("Ship Name");
col.Add("ShipCountry", false).HeaderText("Ship
Country");
})
.Caption("Orders")
.EnablePaging()
.PageSettings(Page => Page.PageSize(12))
.EnableSorting()
.EnableFiltering()
.AutoFormat(Skins.Midnight)
%>
View [cshtml]
@(Html.Syncfusion().Grid<System.Data.DataRow>("OrdersGrid")
.Datasource(Model)
.Column(col =>
{
col.Add("OrderID", false).HeaderText("Order ID");
col.Add("RequiredDate", false).HeaderText("Required
Date");
col.Add("Freight", false) .HeaderText("Freight ");
col.Add("ShipName", false).HeaderText("Ship Name");
col.Add("ShipCountry", false).HeaderText("Ship
Country");
})
.Caption("Orders")
.EnablePaging()
.PageSettings(Page => Page.PageSize(12))
.EnableSorting()
.EnableFiltering()
.AutoFormat(Skins. Midnight)
[Controller]
public ActionResult Datatable()
{
return View(GetTable());
}
var connection =
ConfigurationManager.ConnectionStrings["NORTHWNDConnectionString"].Conn
ectionString;
using (var dataAdapter = new SqlDataAdapter("SELECT * from
Orders", connection))
{
var dataTable = new DataTable();
dataAdapter.Fill(dataTable);
return dataTable;
}
5. In order to work with paging and sorting actions, create a Post method for Index actions
and bind the data source to the grid as shown in the following code.
Controller
/// <summary>
/// Paging/sorting requests are mapped to this method. This
method invokes the HtmlActionResult
/// from the grid. Required response is generated.
/// </summary>
/// <param name="args">Contains paging properties.</param>
/// <returns>
/// HtmlActionResult returns the data displayed on the grid.
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Datatable(PagingParams args)
{
return
GetTable().AsEnumerable().GridActions<System.Data.DataRow>();
}
View [ASPX]
<%=Html.Syncfusion().Grid<DataRow>("StudentGrid", "GridModel",
col =>
{
col.Add("OrderID", false).HeaderText("Order ID");
col.Add("RequiredDate", false).HeaderText("Required
Date");
col.Add("Freight", false);
col.Add("ShipName", false).HeaderText("Ship Name");
col.Add("ShipCountry", false);
}) %>
View [cshtml]
@( Html.Syncfusion().Grid<DataRow>("StudentGrid", "GridModel",
col =>
{
col.Add("OrderID", false).HeaderText("Order ID");
col.Add("RequiredDate", false).HeaderText("Required
Date");
col.Add("Freight", false);
col.Add("ShipName", false).HeaderText("Ship Name");
col.Add("ShipCountry", false);
}))
4. Create a GridPropertiesModel in the Index method. Bind the data source using the
Datasource property and pass the model from the controller to the view using the
ViewData class as given below.
[Controller]
public ActionResult Index()
{
GridPropertiesModel< DataRow > model = new
GridPropertiesModel< DataRow >()
{
DataSource = GetTable().AsEnumerable(),
Caption = "Orders",
AllowPaging = true,
AllowSorting = true
};
ViewData["GridModel"] = model; // Pass the model from
controller to view using ViewData.
return View();
}
5. In order to work with paging and sorting actions, create a Post method for Index actions
and bind the data source to the grid as shown in the following code.
Controller
/// <summary>
/// Paging/sorting requests are mapped to this method. This
method invokes the HtmlActionResult
/// from the grid. Required response is generated.
/// </summary>
/// <param name="args">Contains paging properties.</param>
/// <returns>
/// HtmlActionResult returns the data displayed on the grid.
/// </returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
return
GetTable().AsEnumerable().GridActions<System.Data.DataRow>();
}
In this case, we are choosing the JSON mode for the grid and Excel-like editing to ensure that the
grid is responding to JSON changes.
[View]
@{ Html.Grid<MvcSampleApplication.Models.EditableOrder>("Grid1")
........
........
.ClientSideEvents(c =>
c.QueryCellInfo("Grid1QueryCell") // This adds the
Data-bind attribute to a grid cell.
.OnActionComplete("ActionComplete")
.OnToolbarClickEvent("ToolbarClicked"))
........
........
.Render();
}
Knockout.js is the better choice for dynamic UI updates without any glue-code or events. Here,
the grid is bound with the “Editable Order” model from the server side. Since Knockout.js is
model-based, we have to create a model on the client side also. The code for that is as follows:
[Script]
function OrderViewModel(data) {
// Model properties.
this.OrderID = ko.observable().extend({ AutoUpdate: { "model":
this, "name": "OrderID" } });
this.CustomerID = ko.observable().extend({ AutoUpdate: { "model":
this, "name": "CustomerID" } });
this.EmployeeID = ko.observable().extend({ AutoUpdate: { "model":
this, "name": "EmployeeID" } });
this.Freight = ko.observable().extend({ AutoUpdate: { "model":
this, "name": "Freight" } });
return target;
}
AutoUpdate is the custom extender for observables; it will take care of syncing a JSON data
source between Knockout’s model and the grid’s data source.
We also need another model for storing the list of an OrderViewModel collection and binding it to
a page.
[Script]
function PageViewModel() {
this.dataSource = ko.observableArray([]);
}
For the integration, we are going to write code for setting the data-bind attributes to a grid cell
and binding the grid’s HTML elements to Knockout.js.
[View]
For binding the model, we have to use the grid’s OnActionComplete event, since during initial
rendering the grid didn’t have data in it. Let me show you the code:
[Script]
data source.
function ActionComplete(grid, args) {
ko.cleanNode($(grid.get_element()).find(".GridContent").children().get(
0));
syncJsMap is the Knockout.js extension we are created for converting the JSON data source to
Knockout’s model-based data source. Here is the code I used:
[Script]
We have written some HTML and JavaScript to produce the following functionality:
Upon clicking Change, the concerned JSON data will be updated using Knockout’s ViewModel.
The code for that is as follows:
[Script]
$("#butChange").click(function () {
var rowIndex = parseInt($("#rowIndex").val(), 10);
var columnName = $("#selectColumn").val()
var value = $("#change").val();
// The JSON collection can be changed like this. This will update
the grid's UI as well as the data source.
page.dataSource()[rowIndex][columnName](value);
});
Once Change is clicked, you’ll see the updates in the grid as well. Please refer to the following
screenshot:
You can see in the previous screenshot that the updated row will have a red mark. Click on the
save icon in the grid’s toolbar to store data in the database and clear all dirty items.
W ehave also written a blog pfor this functionality. Please refer to the following blog link:
http://www.syncfusion.com/blogs/post/JSON-Binding-to-MVC-Grid-and-Monitoring-Changes-with-
Knockoutjs.aspx
4.3 Paging
Essential Grid offers complete navigation support to easily switch between the pages using the
pager bar available at the bottom of the Grid control. It facilitates splitting up huge grid data and
displays viewable sets of Grid rows on each page. By selecting the respective page numbers you
can navigate to the other pages. You can also limit the number of pages.
The Grid control for MVC exposes the following properties and methods to enable and control the
paging feature.
Properties
Methods
CurrentPage(Int32) Set the current page to the Grid control. Current page IPagerBuilder
number as
integer
1. Create a model in the application (refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (refer to How to>Strongly Typed View)
3. In the view you can use its Model property in Datasource() in order to bind the data
source.
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Column( columns => {
columns.Add(p => p.OrderID).HeaderText("Order ID");
columns.Add(p => p.CustomerID).HeaderText("Customer ID");
columns.Add(p => p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship Country");
columns.Add(p => p.ShipCity).HeaderText("Ship City");
})%>
View [cshtml]
@{ Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Column( columns => {
columns.Add(p => p.OrderID).HeaderText("Order ID");
columns.Add(p => p.CustomerID).HeaderText("Customer ID");
columns.Add(p => p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship Country");
columns.Add(p => p.ShipCity).HeaderText("Ship City");
}.Render();
}
4. To enable the paging feature for your grid you should use the EnablePaging() method.
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.EnablePaging()
.Column( columns => {
columns.Add(p => p.OrderID).HeaderText("Order ID");
columns.Add(p => p.CustomerID).HeaderText("Customer ID");
columns.Add(p => p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship
Country");
View [cshtml]
@{ Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.EnablePaging()
.Column( columns => {
columns.Add(p => p.OrderID).HeaderText("Order ID");
columns.Add(p => p.CustomerID).HeaderText("Customer ID");
columns.Add(p => p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship
Country");
columns.Add(p => p.ShipCity).HeaderText("Ship City");
}).Render();
}
5. Set its data source and render the view.
Controller
/// <summary>
/// Used to bind the grid.
/// </summary>
/// <returns>View page; it displays the grid.</returns>
public ActionResult Index()
{
var data = new NorthwindDataContext().Orders;
return View(data);
}
6. In order to work with paging actions, create a Post method for Index actions and bind the
data source to the grid as given in the following code.
Controller
/// <summary>
/// Paging/sorting requests are mapped to this method. This
method invokes the HtmlActionResult
/// from the grid. Required response is generated.
/// </summary>
/// <param name="args">Contains paging properties. </param>
/// <returns>
/// HtmlActionResult returns the data displayed on the grid.
/// </returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new NorthwindDataContext().Orders;
return data.GridActions<Order>();
}
If you want to enable or disable the paging based on some condition, use the
AllowPaging(bool) method.
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders Details")
.EnablePaging()
.PageSettings(paging => paging.AllowPaging(true))
%>
If you want to change the page size, use the PageSize(Int32) method.
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders Details")
.PageSettings(paging => paging.PageSize(20))
%>
View [cshtml]
@{ Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders Details")
.PageSettings(paging => paging.PageSize(20))
.Render();
If you want to change the number of visible pages counted in the pager bar, use the
PageCount(Int32) method.
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders Details")
.EnablePaging()
.PageSettings(paging => paging.PageCount(5))
%>
View [cshtml]
@{ Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders Details")
.EnablePaging()
.PageSettings(paging => paging.PageCount(5))
.Render();
}
If you want to render the grid with initial paging, use the CurrentPage(Int32)
method.
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders Details")
.EnablePaging()
.PageSettings(paging => paging.CurrentPage(3))
%>
View [cshtml]
@{ Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders Details")
.EnablePaging()
.PageSettings(paging => paging.CurrentPage(3))
.Render();
}
1. Create a model in the application (refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (refer to How to>Strongly Typed View).
3. Add the following code in the Index.aspx file to create the Grid control in the view.
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("SortingGrid","GridModel",
columns => {
columns.Add(p => p.OrderID).HeaderText("Order
ID");
columns.Add(p =>
p.CustomerID).HeaderText("Customer ID");
columns.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
columns.Add(P =>
P.ShipCountry).HeaderText("Ship Country");
columns.Add(p => p.ShipCity).HeaderText("Ship
City");
})%>
View [cshtml]
@( Html.Syncfusion().Grid<Order>("SortingGrid","GridModel", columns => {
columns.Add(p => p.OrderID).HeaderText("Order
ID");
columns.Add(p =>
p.CustomerID).HeaderText("Customer ID");
columns.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
columns.Add(P =>
P.ShipCountry).HeaderText("Ship Country");
columns.Add(p => p.ShipCity).HeaderText("Ship
City");
}))
Controller
public ActionResult Index()
{
GridPropertiesModel<Order> gridModel = new
GridPropertiesModel<Order>()
{
DataSource=new NorthwindDataContext().Orders,
Caption="Orders",
AllowPaging=true
};
ViewData["GridModel"] = gridModel; // Pass the model from
controller to view using ViewData.
return View();
}
5. In order to work with paging actions, create a Post method for Index actions and bind the
data source to the grid as shown in the following code.
Controller
/// <summary>
/// Paging/sorting requests are mapped to this method. This
method invokes the HtmlActionResult
/// from the grid. The required response is generated.
/// </summary>
/// <param name="args">Contains paging properties.</param>
/// <returns>
/// HtmlActionResult returns the data displayed on the grid.
/// </returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new NorthwindDataContext().Products;
return data.GridActions<Product>();
}
If you want to change the page size, use the PageSize property.
Controller
If you want to change the number of visible pages counted in the pager bar, use the
PageCount property.
10.
Controller
If you want to render the grid with initial paging, use the CurrentPage property.
Controller
Sample Link
To view the samples, follow the steps below:
1. Open the Grid sample browser from the dashboard (Refer to the Samples and Location
chapter).
2. Navigate to Grid.MVC > Paging > Server Mode
1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. Create the Grid control in the view and configure its properties.
4. Set the JSON action mode using the ActionMode method.
5. Enable paging using the EnablePaging method.
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("Grid1")
.Caption("Orders")
.AutoFormat(Skins.Sandune)
.ActionMode(ActionMode.JSON)
.EnablePaging()
.Column( columns => {
columns.Add(p => p.OrderID);
columns.Add(p => p.CustomerID);
columns.Add(p => p.EmployeeID);
columns.Add(P => P.ShipCountry);
columns.Add(p => p.OrderDate).Format("{0:dd-MM-yyyy}");
})
%>
View [cshtml]
@{ Html.Syncfusion().Grid<Order>("Grid1")
.Caption("Orders")
.AutoFormat(Skins.Sandune)
.ActionMode(ActionMode.JSON)
.EnablePaging()
.Column( columns => {
columns.Add(p => p.OrderID);
columns.Add(p => p.CustomerID);
columns.Add(p => p.EmployeeID);
columns.Add(P => P.ShipCountry);
columns.Add(p => p.OrderDate).Format("{0:dd-MM-yyyy}");
}).Render();
}
Controller
public ActionResult Index()
{
return View();
}
7. In order to work with paging actions, create a Post method for Index actions and bind the
data source to the grid as given in the following code sample.
Controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new NorthwindDataContext().Orders.ToList();
return data.GridJSONActions<Order>();
}
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("Grid1")
.Caption("Orders Details")
.ActionMode(ActionMode.JSON)
.EnablePaging()
.PageSettings(paging => paging.AllowPaging(true))
%>
View [cshtml]
@{ Html.Syncfusion().Grid<Order>("Grid1")
.Caption("Orders Details")
.ActionMode(ActionMode.JSON)
.EnablePaging()
.PageSettings(paging => paging.AllowPaging(true))
.Render();
}
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("Grid1")
.Caption("Orders Details")
.ActionMode(ActionMode.JSON)
.PageSettings(paging => paging.PageSize(20))
%>
View [cshtml]
@{ Html.Syncfusion().Grid<Order>("Grid1")
.Caption("Orders Details")
.ActionMode(ActionMode.JSON)
.PageSettings(paging => paging.PageSize(20))
.Render();
}
To change the number of visible pages counted in the pager bar, use the
PageCount(Int32) method.
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("Grid1")
.Caption("Orders Details")
.EnablePaging()
.PageSettings(paging => paging.PageCount(5))
%>
View [cshtml]
@{ Html.Syncfusion().Grid<Order>("Grid1")
.Caption("Orders Details")
.EnablePaging()
.PageSettings(paging => paging.PageCount(5))
.Render();
}
If you want to render the grid with initial paging, use the CurrentPage(Int32) method.
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("Grid1")
.Caption("Orders Details")
.ActionMode(ActionMode.JSON)
.EnablePaging()
.PageSettings(paging => paging.CurrentPage(3))
%>
View [cshtml]
@{ Html.Syncfusion().Grid<Order>("Grid1")
.Caption("Orders Details")
.ActionMode(ActionMode.JSON)
.EnablePaging()
.PageSettings(paging => paging.CurrentPage(3))
.Render();
}
View [cshtml]
@( Html.Syncfusion().Grid<Order>("Grid1","GridModel", columns => {
columns.Add(p => p.OrderID)
columns.Add(p => p.CustomerID)
columns.Add(p => p.EmployeeID);
columns.Add(P => P.ShipCountry);
columns.Add(p => p.OrderDate).Format("{0:dd-MM-yyyy}");
})
)
4. Create a GridPropertiesModel in the Index method. Use the ActionMode property to set
JSON mode.
5. Use the AllowPaging property to enable the paging operations.
[Controller]
};
ViewData["GridModel"] = gridModel;
return View();
}
6. In order to work with paging actions, create a Post method for Index actions and bind the
data source to the grid as shown in the following code.
Controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new NorthwindDataContext().Orders.ToList();
return data.GridJSONActions<Order>();
}
Controller
{
ActionMode = ActionMode.JSON,
Caption = "Orders Details",
AllowPaging = true,
PageSize=20
};
To change the number of visible pages counted in the pager bar, use the PageCount
property.
Controller
If you want to render the grid with initial paging, use the CurrentPage property.
Controller
Sample Link
To view the samples, follow the steps below:
1. Open the ASP.NET MVC sample browser from the dashboard. (Refer to the Samples and
Location chapter)
2. Navigate to Grid>Paging>JSON Mode.
11.
Essential Grid supports twelve different types of built-in pager styles. They are:
Default
Advanced
DefaultAndAdvanced
DefaultAndManual
Manual
Numeric
PrevAndNext
PrevNextAndAdvanced
PrevNextAndManual
Slider
SliderAndAdvanced
SliderAndManual
The position of the pager can be customized using the following four options:
BottomLeft
BottomRight
TopLeft
TopRight
1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. In the view you can use its Model property in Datasource() to bind the data source.
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("OrderGrid")
.Datasource(Model)
.Caption("Orders")
.AutoFormat(Skins.Almond)
.Column(col =>
{
col.Add(c => c.OrderID)
col.Add(c => c.EmployeeID)
col.Add(c => c.ShipCountry)
col.Add(c => c.ShipCity;
col.Add(c => c.CustomerID);
})
.PageSettings(page =>
{
page.AllowPaging(true);
page.PagerStyle(PagerStyle.Slider);
page.PagerPosition(Position.TopLeft);
page.ShowPagerInformation(true);
})
%>
View [cshtml]
@{ Html.Syncfusion().Grid<MVCSampleBrowser.Models.Order>("OrderGrid")
.Datasource(Model)
.Caption("Orders")
.AutoFormat(Skins.Almond)
.Column(col =>
{
col.Add(c => c.OrderID);
col.Add(c => c.EmployeeID);
col.Add(c => c.ShipCountry);
col.Add(c => c.ShipCity );
col.Add(c => c.CustomerID);
})
.PageSettings(page =>
{
page.AllowPaging(true);
page.PagerStyle(PagerStyle.Slider);
page.PagerPosition(Position.TopLeft);
page.ShowPagerInformation(true);
}).Render();
Controller
/// <summary>
/// Used to bind the grid.
/// </summary>
/// <returns>View page; it displays the grid.</returns>
public ActionResult Index()
{
var data = new NorthwindDataContext().Orders.ToList();
return View(data);
}
5. Run the application. The grid will appear as shown in the following screenshot.
1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. Add the following code in the Index.aspx file to create the Grid control in the view.
View [ASPX]
View [cshtml]
@( Html.Syncfusion().Grid<Order>("OrderGrid", col=>
{
col.Add(c => c.OrderID);
col.Add(c => c.EmployeeID);
col.Add(c => c.ShipCountry);
col.Add(c => c.ShipCity );
5. Run the application. The grid will appear as shown in the following screenshot:
Properties
PagerStyle.DefaultAn
dAdvanced
PagerStyle.DefaultAn
dManual
PagerStyle.Manual
PagerStyle.Numeric
PagerStyle.PrevAnd
Next
PagerStyle.PrevNext
AndAdvanced
PagerStyle.PrevNext
AndManual
PagerStyle.Slider
PagerStyle.SliderAnd
Advanced
PagerStyle.SliderAnd
Manual
Sample Link
To view the samples, follow the steps below:
1. Open the Grid sample browser from the dashboard (Refer to the Samples and Location
chapter).
2. Navigate to Grid.MVC > Paging > Pager Types
4.4 Sorting
Sorting is defined as the process of arranging items/records in some ordered sequence. Essential
Grid supports arranging table data in ascending ( ) or descending ( ) order based on the
column header that is clicked. The order switches between ascending and descending each time
you click a column header for sorting.
Properties
individual
columns.
1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. In the view you can use its Model property in Datasource() to bind the data source.
12.
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.EnablePaging()
.AutoFormat(Skins.Sandune)
.Column( columns => {
columns.Add(p => p.OrderID).HeaderText("Order
ID");
columns.Add(p =>
p.CustomerID).HeaderText("Customer ID");
columns.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship
Country");
columns.Add(p => p.ShipCity).HeaderText("Ship
City");
})%>
View [cshtml]
@{ Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.EnablePaging()
.AutoFormat(Skins.Sandune)
.Column( columns => {
columns.Add(p => p.OrderID).HeaderText("Order
ID");
columns.Add(p =>
p.CustomerID).HeaderText("Customer ID");
columns.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship
Country");
columns.Add(p => p.ShipCity).HeaderText("Ship
City");
}).Render();
}
4. To enable the sorting feature for your grid you should use the EnableSorting() method.
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.EnableSorting()
.EnablePaging()
.AutoFormat(Skins.Sandune)
.Column( columns => {
columns.Add(p => p.OrderID).HeaderText("Order
ID");
columns.Add(p =>
p.CustomerID).HeaderText("Customer ID");
columns.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship
Country");
columns.Add(p => p.ShipCity).HeaderText("Ship
City");
})%>
View [cshtml]
@{ Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.EnableSorting()
.EnablePaging()
.AutoFormat(Skins.Sandune)
.Column( columns => {
columns.Add(p => p.OrderID).HeaderText("Order
ID");
columns.Add(p =>
p.CustomerID).HeaderText("Customer ID");
columns.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship
Country");
columns.Add(p => p.ShipCity).HeaderText("Ship
City");
}).Render();
}
Controller
/// <summary>
/// Used to bind the grid.
/// </summary>
/// <returns>View page; it displays the grid.</returns>
public ActionResult Index()
{
var data = new NorthwindDataContext().Orders;
return View(data);
}
6. In order to work with sorting actions, create a Post method for Index actions and bind the
data source to the grid as shown in the following code.
Controller
/// <summary>
/// Paging/sorting requests are mapped to this method. This
method invokes the HtmlActionResult
/// from the grid. Required response is generated.
/// </summary>
/// <param name="args">Contains paging properties.</param>
/// <returns>
/// HtmlActionResult returns the data displayed on the grid.
/// </returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new NorthwindDataContext().Orders;
return data.GridActions<Order>();
}
If you want to enable or disable the sorting based on some condition, use
AllowSorting(bool) method.
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.EnablePaging()
.SortSettings( sort => sort.AllowSorting(true))
%>
View [cshtml]
@{ Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.EnablePaging()
.SortSettings( sort => sort.AllowSorting(true))
.Render();
}
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.EnablePaging()
.SortSettings( sort => sort.AllowMultiSorting(true))
%>
View [cshtml]
@{ Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.EnablePaging()
.SortSettings( sort => sort.AllowMultiSorting(true))
.Render();
}
If you want to render the grid with initial sorting, use the SortDescriptors() method.
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.EnablePaging()
.SortSettings(sort =>
sort. SortDescriptors(column => {
column.Add(c => c.CustomerID);
}
))
%>
View [cshtml]
@{ Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.EnablePaging()
.SortSettings(sort =>
sort. SortDescriptors(column => {
column.Add(c => c.CustomerID);
}
)).Render();
}
If you want to render the grid with initial sorting in a specific direction, use the
SortDescriptors() method.
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.EnablePaging()
.SortSettings(sort =>
sort. SortDescriptors(column => {
column.Add(c =>
c.CustomerID,System.ComponentModel.ListSortDirection.Descending); }
))
%>
View [cshtml]
@{ Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.EnablePaging()
.SortSettings(sort =>
sort. SortDescriptors(column => {
column.Add(c =>
c.CustomerID,System.ComponentModel.ListSortDirection.Descending); }
)).Render();
}
1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. Add the following code in the Index.aspx file to create the Grid control in the view.
View [ASPX]
View [cshtml]
@( Html.Syncfusion().Grid<Order>("SortingGrid","GridModel", columns =>
{
columns.Add(p => p.OrderID).HeaderText("Order
ID");
columns.Add(p =>
p.CustomerID).HeaderText("Customer ID");
columns.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
columns.Add(P =>
P.ShipCountry).HeaderText("Ship Country");
columns.Add(p => p.ShipCity).HeaderText("Ship
City");
}))
Controller
5. In order to work with sorting actions, create a Post method for Index actions and bind the
data source to the grid as given in the following code sample.
Controller
/// <summary>
/// Paging/sorting requests are mapped to this method. This
method invokes the HtmlActionResult
/// from the grid. The required response is generated.
/// </summary>
/// <param name="args">Contains paging properties.</param>
/// <returns>
/// HtmlActionResult returns the data displayed on the grid.
/// </returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new NorthwindDataContext().Products;
return data.GridActions<Product>();
}
6. Run the application. The grid will appear as shown below.
If you want to enable or disable the multi-sort feature, use the AllowMultiSorting
property.
Controller
If you want to render the grid with initial sorting use the SortDescriptors property.
/// <summary>
/// Used for rendering the grid initially.
/// </summary>
/// <returns>View page, it displays the grid.</returns>
public ActionResult Index()
{
GridPropertiesModel<Order> gridModel = new
GridPropertiesModel<Order>()
{
DataSource = new NorthwindDataContext().Orders,
Caption = "Orders",
AllowPaging = true,
AllowSorting=true,
AllowMultiSorting=true,
AutoFormat=Skins.Sandune
};
ViewData["GridModel"] = gridModel;
return View();
}
If you want to render the grid with initial sorting with direction use the SortDescriptors
property.
/// <summary>
/// Used for rendering the grid initially.
/// </summary>
/// <returns>View page, it displays the grid.</returns>
public ActionResult Index()
{
GridPropertiesModel<Order> gridModel = new
GridPropertiesModel<Order>()
{
DataSource = new NorthwindDataContext().Orders,
Caption = "Orders",
AllowPaging = true,
AllowSorting=true,
AllowMultiSorting=true,
AutoFormat=Skins.Sandune
};
sort.SortDirection =
System.ComponentModel.ListSortDirection.Descending;
Sample Link
To view the samples, follow the steps below:
1. Open the Grid sample browser from the dashboard (Refer to the Samples and Location
chapter).
2. Navigate to Grid.MVC > Sorting > Server Mode
13. High performance: The grid will be quickly rendered because of client-side rendering.
14. Encapsulation: Objects are encapsulated to another object for security.
15. Reduction of post back time: On the server side, rendering grid content does not happen
which will reduce the postback time.
1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. Create the Grid control in the view and configure its properties.
4. Set the JSON action mode using the ActionMode method.
5. Enable sorting using the EnableSorting method.
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("Grid1")
.Caption("Orders")
.AutoFormat(Skins.Sandune)
.ActionMode(ActionMode.JSON)
.EnableSorting()
.Column( columns => {
View [cshtml]
@{ Html.Syncfusion().Grid<Order>("Grid1")
.Caption("Orders")
.AutoFormat(Skins.Sandune)
.ActionMode(ActionMode.JSON)
.EnableSorting()
.Column( columns => {
columns.Add(p => p.OrderID);
columns.Add(p => p.CustomerID);
columns.Add(p => p.EmployeeID);
columns.Add(P => P.ShipCountry);
columns.Add(p => p.OrderDate).Format("{0:dd-MM-yyyy}");
}).Render();
}
Controller
7. In order to work with sorting actions, create a Post method for Index actions and bind the
data source to the grid as shown in the code below.
Controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new
NorthwindDataContext().Orders.ToList();
return data.GridJSONActions<Order>();
}
To enable and disable the sorting feature use the AllowSorting(bool) method.
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("Grid1")
.Caption("Orders")
.ActionMode(ActionMode.JSON)
.SortSettings( sort => sort.AllowSorting(true))
%>
View [cshtml]
@{ Html.Syncfusion().Grid<Order>("Grid1")
.Caption("Orders")
.ActionMode(ActionMode.JSON)
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("Grid1")
.Caption("Orders")
.ActionMode(ActionMode.JSON)
.SortSettings( sort => sort.AllowMultiSorting(true))
%>
View [cshtml]
@{ Html.Syncfusion().Grid<Order>("Grid1")
.Caption("Orders")
.ActionMode(ActionMode.JSON)
.SortSettings( sort =>
sort.AllowMultiSorting(true))
.Render();
}
To render the grid with initial sorting, use the SortDescriptors() method.
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("Grid1")
.Caption("Orders")
.ActionMode(ActionMode.JSON)
.SortSettings(sort =>
sort.SortDescriptors(column => {
column.Add(c => c.CustomerID);
}
))
%>
View [cshtml]
@{ Html.Syncfusion().Grid<Order>("Grid1")
.Caption("Orders")
.ActionMode(ActionMode.JSON)
.SortSettings(sort =>
sort.SortDescriptors(column => {
column.Add(c => c.CustomerID);
}
)).Render();
}
To render the grid with initial sorting in a specific direction, use the
SortDescriptors() method.
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("Grid1")
.Caption("Orders")
.ActionMode(ActionMode.JSON)
.SortSettings(sort =>
sort.SortDescriptors(column => {
column.Add(c =>
c.CustomerID,System.ComponentModel.ListSortDirection.Descending); }
))
%>
.
View [cshtml]
@{ Html.Syncfusion().Grid<Order>("Grid1")
.Caption("Orders")
.ActionMode(ActionMode.JSON)
.SortSettings(sort =>
sort.SortDescriptors(column => {
column.Add(c =>
c.CustomerID,System.ComponentModel.ListSortDirection.Descending); }
)).Render();
}
1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. Add the following code in the Index.aspx file to create the Grid control in the view.
View [ASPX]
View [cshtml]
4. Create a GridPropertiesModel in the Index method. Use the ActionMode property to set
the JSON mode.
5. Use the AllowSorting property to enable the sorting operations.
[Controller]
public ActionResult Index()
{
GridPropertiesModel<Order> gridModel = new
GridPropertiesModel<Order>()
{
Caption = "Orders",
AutoFormat = Syncfusion.Mvc.Shared.Skins.Sandune,
AllowSorting = true,
ActionMode = ActionMode.JSON
};
ViewData["GridModel"] = gridModel;
return View();
}
6. In order to work with sorting actions, create a Post method for Index actions and bind the
data source to the grid as given in the following code.
Controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new
NorthwindDataContext().Orders.ToList();
return data.GridJSONActions<Order>();
}
Controller
};
To render the grid with initial sorting, use the SortDescriptors property.
ViewData["GridModel"] = gridModel;
return View();
}
To render the grid with initial sorting in a specific direction, use the SortDescriptors
property.
property.
gridModel.SortDescriptors.Add(sort);
ViewData["GridModel"] = gridModel;
return View();
}
Sample Link
To view the samples, follow the steps below:
1. Open the ASP.NET MVC sample browser from the dashboard. (Refer to the Samples and
Location chapter)
2. Navigate to Grid>Sorting>JSON Mode.
4.5 Filtering
Essential Grid allows you to restrict the display of records using a mechanism called filters. A filter
facilitates the extraction of a subset of records that meet certain criteria. Filters can be applied to
one or more columns. This is very useful when dealing with large data sets. Essential Grid
provides both advanced filter and check box drop-down filter options by default.
When this feature is enabled, every column header displays a filter icon. Clicking this icon opens
a menu with a subset of check boxes in a drop-down list and submenu items for advanced
filtering.
Drop-Down Filters:
Clicking on a filter icon opens a menu with a subset of drop-down list items that holds the
possible filter values for the column clicked. To filter the data by a specific value, just select the
list box item that prefixes the desired filter value and click the OK button to apply filters. This will
then reload the grid with only those records that have the selected value in the column.
Advanced Filters:
Clicking on a filter icon opens a menu and submenu items. Submenu items in the filter menu
provide the advanced filtering options for end users. When selecting a sub menu item, a separate
dialog box opens and displays an advanced filter drop-down that lists the available filter operators
for the respective filtering column. Selecting a submenu item also provides text boxes that allow
you to type a filter string. It performs the filter operation by clicking the OK button.
Properties
Any other
dependenci
Type of
Property Description Value it accepts es/associat
property
ed sub-
properties
Enables the
grouping
AllowFiltering feature. boolean True/False NA
Default value is
False.
Collection that is
used to add and List<FilterD
apply filter escriptor> Dependent on
FilterDescriptors
conditions AllowFiltering.
programmaticall
y at initial load.
FilterType
.LessThan
FilterType .LessThanOrEqual
FilterType
.Equals
FilterType
Gets or sets the .NotEquals
Operator operator for a Enum
filter descriptor. FilterType
.GreaterThanOrEqual
FilterType
.GreaterThan
FilterType .StartsWith
FilterType .EndsWith
FilterType .Contains
Methods
Sample Link
To view the samples:
1. Open the ASP.NET MVC sample browser from the dashboard (Refer to the Samples and
Location chapter).
2. Navigate to Grid>Filtering to browse the filtering demos.
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.EnablePaging()
.EnableSorting()
.EnableFiltering()
.AutoFormat(Skins.Sandune)
.Column( columns => {
columns.Add(p => p.OrderID).HeaderText("Order ID");
columns.Add(p => p.CustomerID).HeaderText("Customer ID");
columns.Add(p => p.EmployeeID).HeaderText("Employee ID");
View [cshtml]
@{ Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.EnablePaging()
.EnableSorting()
.EnableFiltering()
.AutoFormat(Skins.Sandune)
.Column( columns => {
columns.Add(p => p.OrderID).HeaderText("Order ID");
columns.Add(p => p.CustomerID).HeaderText("Customer ID");
columns.Add(p => p.EmployeeID).HeaderText("Employee ID");
4. To enable the filtering feature for your grid, you should use the EnableFiltering() method.
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.EnablePaging()
.EnableSorting()
.EnableFiltering()
.AutoFormat(Skins.Sandune)
.Column( columns => {
columns.Add(p => p.OrderID).HeaderText("Order ID");
columns.Add(p => p.CustomerID).HeaderText("Customer ID");
columns.Add(p => p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship Count
ry");
columns.Add(p => p.OrderDate).HeaderText("Order Date");
})
%>
View [cshtml]
@{ Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.EnablePaging()
.EnableSorting()
.EnableFiltering()
.AutoFormat(Skins.Sandune)
.Column( columns => {
columns.Add(p => p.OrderID).HeaderText("Order ID");
columns.Add(p => p.CustomerID).HeaderText("Customer ID");
columns.Add(p => p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship Count
ry");
columns.Add(p => p.OrderDate).HeaderText("Order Date");
}).Render();
}
[Controller]
/// <summary>
/// Used for rendering the grid initially.
/// </summary>
/// <returns>View page; it displays the grid.</returns>
public ActionResult Index()
{
var data = new NorthwindDataContext().Orders;
return View(data);
}
6. In order to work with filter actions, create a Post method for Index actions and bind the data
source to the grid as shown in the following code.
[Controller]
/// <summary>
/// Paging/sorting/filtering requests are mapped to this method
. This method invokes the HtmlActionResult
/// from the grid. The required response is generated.
/// </summary>
/// <param name="args">Contains paging properties.</param>
/// <returns>
/// HtmlActionResult returns the data displayed on the grid.
/// </returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new NorthwindDataContext().Orders;
return data.GridActions<Order>();
}
7. Run the application. The grid will appear as shown in the following screenshot.
If you want to enable or disable the filter based on some condition, use the
AllowFiltering(bool) method:
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.EnablePaging()
.EnableSorting()
.Filtering(filter =>
{
filter.AllowFiltering(true);
})
%>
View [cshtml]
@{ Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.EnablePaging()
.EnableSorting()
.Filtering(filter =>
{
filter.AllowFiltering(true);
}).Render();
}
If you want to enable or disable the filter options for individual columns, use the
AllowFilter(bool) method in column mapping.
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.EnablePaging()
.EnableSorting()
.EnableFiltering()
.AutoFormat(Skins.Sandune)
.Column( columns => {
columns.Add(p => p.OrderID).HeaderText("Order ID").AllowFilter(f
alse);
columns.Add(p => p.CustomerID).HeaderText("Customer ID");
columns.Add(p => p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship Country")
;
columns.Add(p => p.OrderDate).HeaderText("Order Date");
})
%>
View [cshtml]
@{ Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.EnablePaging()
.EnableSorting()
.EnableFiltering()
.AutoFormat(Skins.Sandune)
.Column( columns => {
columns.Add(p => p.OrderID).HeaderText("Order ID").AllowFilter(f
alse);
columns.Add(p => p.CustomerID).HeaderText("Customer ID");
columns.Add(p => p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship Country")
;
columns.Add(p => p.OrderDate).HeaderText("Order Date");
}).Render();
If you want to render the filter menu in a simple drop-down list, use the
FilterDropDownType() method.
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.EnablePaging()
.EnableSorting()
.Filtering(filter =>
{
filter.FilterDropDownType(FilterDropDownType.SimpleList)
;
})
%>
View [cshtml]
@{ Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.EnablePaging()
.EnableSorting()
.Filtering(filter =>
{
filter.FilterDropDownType(FilterDropDownType.SimpleList)
;
}).Render();
}
There are two ways to specify the initial filters information namely:
Use the Filtering() method to add the initial filters.
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.EnablePaging()
.EnableSorting()
.Filtering(filter =>
{
filter.FilterDescriptors(descriptor =>
{
descriptor.Add(c => c.EmployeeID).FilterBy(FilterType.Equals).F
ilterValue(5);
});
})
.AutoFormat(Skins.Sandune)
.Column( columns => {
columns.Add(p => p.OrderID).HeaderText("Order ID").AllowFilter(f
alse);
columns.Add(p => p.CustomerID).HeaderText("Customer ID");
columns.Add(p => p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship Country")
;
columns.Add(p => p.OrderDate).HeaderText("Order Date");
})
%>
View [cshtml]
@{ Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.EnablePaging()
.EnableSorting()
.Filtering(filter =>
{
filter.FilterDescriptors(descriptor =>
{
descriptor.Add(c => c.EmployeeID).FilterBy(FilterType.Equals).F
ilterValue(5);
});
})
.AutoFormat(Skins.Sandune)
.Column( columns => {
columns.Add(p => p.OrderID).HeaderText("Order ID").AllowFilter(f
alse);
columns.Add(p => p.CustomerID).HeaderText("Customer ID");
columns.Add(p => p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship Country")
;
columns.Add(p => p.OrderDate).HeaderText("Order Date");
}).Render();
}
Through GridPropertiesModel
a. Create GridPropertiesModel in Controller Index action and add the initial filters
using the FilterDescriptors property.
[Controller]
b. Pass the GridPropertiesModel to the view using the ViewData() method. Use the grid’s
ID as the key in ViewData.
[Controller]
1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
16. Add the following code in the Index.aspx file to create the Grid control in the view.
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("FilteringGrid","GridModel", columns =
> {
columns.Add(p => p.OrderID).HeaderText("Order ID");
columns.Add(p => p.CustomerID).HeaderText("Customer ID");
columns.Add(p => p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship Country");
columns.Add(p => p.OrderDate).HeaderText("Order Date").Form
at("{0:dd-MM-yyyy}");
})%>
View [cshtml]
@( Html.Syncfusion().Grid<Order>("FilteringGrid","GridModel",
columns => {
columns.Add(p => p.OrderID).HeaderText("Order ID");
columns.Add(p => p.CustomerID).HeaderText("Customer ID");
columns.Add(p => p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship Country");
columns.Add(p => p.OrderDate).HeaderText("Order Date").Form
at("{0:dd-MM-yyyy}");
}))
[Controller]
/// <summary>
/// Used for rendering the grid initially.
/// </summary>
/// <returns>View page; it displays the grid.</returns>
public ActionResult Filtering()
{
GridPropertiesModel<Order> gridModel = new GridPropertiesMo
del<Order>()
{
DataSource = new NorthwindDataContext().Orders,
Caption = "Orders",
AllowPaging = true,
AllowSorting = true,
AllowFiltering = true,
AutoFormat = Skins.Sandune
};
ViewData["GridModel"] = gridModel;
return View();
}
5. In order to work with filtering actions, create a Post method for Index actions and bind the
data source to the grid as shown in the following code sample.
[Controller]
/// <summary>
/// Paging requests are mapped to this method. This method invo
kes the HtmlActionResult
/// from the grid. The required response is generated.
/// </summary>
/// <param name="args">Contains paging properties.</param>
/// <returns>
/// HtmlActionResult returns the data displayed on the grid.
/// </returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Filtering(PagingParams args)
{
IEnumerable data = new NorthwindDataContext().Orders;
return data.GridActions<Order>();
}
6. Run the application. The grid will appear as shown in the following screenshot.
<%=Html.Syncfusion().Grid<Order>("FilteringGrid","GridModel", columns =
> {
columns.Add(p => p.OrderID).HeaderText("Order ID").AllowFil
ter(false);
columns.Add(p => p.CustomerID).HeaderText("Customer ID");
columns.Add(p => p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship Country");
columns.Add(p => p.OrderDate).HeaderText("Order Date").Form
at("{0:dd-MM-yyyy}");
})%>
View [cshtml]
@( Html.Syncfusion().Grid<Order>("FilteringGrid","GridModel",
columns => {
columns.Add(p => p.OrderID).HeaderText("Order ID").AllowFil
ter(false);
columns.Add(p => p.CustomerID).HeaderText("Customer ID");
columns.Add(p => p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship Country");
If you want to render the filter menu in a simple drop-down list, then use the
FilterDropDownType property.
[Controller]
// Create GridPropertiesModel.
GridPropertiesModel<Order> gridModel = new GridPropertiesModel<Or
der>();
If you want to render the grid with initial filtering, add the filter conditions using the
FilterDescriptors property.
[Controller]
// Create GridPropertiesModel.
GridPropertiesModel<Order> gridModel = new GridPropertiesModel<Or
der>();
If you want to render the grid with initial filtering, add the filter conditions using the
FilterDescriptors property.
[Controller]
AllowFiltering = true,
AutoFormat = Skins.Sandune
};
// Apply intial filters to the grid.
gridModel.Filters.FilterDescriptors.Add(new FilterDescriptor() { C
olumnName = "EmployeeID", Operator = Syncfusion.Linq.FilterType.Equals,
Value = 5 });
ViewData["GridModel"] = gridModel;
return View();
}
Sample Link
To view the samples, follow the steps below:
1. Open the Grid sample browser from the dashboard (Refer to the Samples and Location
chapter).
2. Navigate to Grid.MVC > Filtering > Server Mode
1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. Create the Grid control in the view and configure its properties.
4. Set the JSON action mode using the ActionMode method.
5. Enable filtering using the EnableFiltering() method.
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("Grid1")
.Caption("Orders")
.AutoFormat(Skins.Sandune)
.ActionMode(ActionMode.JSON)
.EnableFiltering()
.Column( columns => {
columns.Add(p => p.OrderID);
columns.Add(p => p.CustomerID);
columns.Add(p => p.EmployeeID);
columns.Add(P => P.ShipCountry);
columns.Add(p => p.OrderDate).Format("{0:dd-MM-yyyy}");
})
%>
View [cshtml]
@{ Html.Syncfusion().Grid<Order>("Grid1")
.Caption("Orders")
.AutoFormat(Skins.Sandune)
.ActionMode(ActionMode.JSON)
.EnableFiltering()
.Column( columns => {
columns.Add(p => p.OrderID);
columns.Add(p => p.CustomerID);
columns.Add(p => p.EmployeeID);
columns.Add(P => P.ShipCountry);
columns.Add(p => p.OrderDate).Format("{0:dd-MM-yyyy}");
}).Render();
}
Controller
7. In order to work with filtering actions, create a Post method for Index actions and bind the
data source to the grid as given in the following code sample.
Controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new NorthwindDataContext().Orders.ToList();
return data.GridJSONActions<Order>();
}
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("Grid1")
.ActionMode(ActionMode.JSON)
.Caption("Orders")
.EnablePaging()
.EnableSorting()
.Filtering(filter =>
{
filter.AllowFiltering(true);
})
%>
View [cshtml]
@{ Html.Syncfusion().Grid<Order>("Grid1")
.ActionMode(ActionMode.JSON)
.Caption("Orders")
.EnablePaging()
.EnableSorting()
.Filtering(filter =>
{
filter.AllowFiltering(true);
}).Render();}
To enable or disable filter options for individual columns, use the AllowFilter(bool)
method in column mapping.
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("Grid1")
.ActionMode(ActionMode.JSON)
.Caption("Orders")
.EnableFiltering()
.AutoFormat(Skins.Sandune)
.Column( columns => {
columns.Add(p => p.OrderID).HeaderText("Order ID").AllowFilter(false)
;
columns.Add(p => p.CustomerID).HeaderText("Customer ID");
columns.Add(p => p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship Country");
columns.Add(p => p.OrderDate).HeaderText("Order Date");
})
%>
View [cshtml]
@{ Html.Syncfusion().Grid<Order>("Grid1")
.ActionMode(ActionMode.JSON)
.Caption("Orders")
.EnableFiltering()
.AutoFormat(Skins.Sandune)
.Column( columns => {
columns.Add(p => p.OrderID).HeaderText("Order ID").AllowFilter(false)
;
columns.Add(p => p.CustomerID).HeaderText("Customer ID");
columns.Add(p => p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship Country");
columns.Add(p => p.OrderDate).HeaderText("Order Date");
}).Render();
}
To render the filter menu in a simple drop-down list, use the FilterDropDownType()
method.
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("Grid1")
.Caption("Orders")
.Filtering(filter =>
{
filter.FilterDropDownType(FilterDropDownType.SimpleList);
})
%>
View [cshtml]
@{ Html.Syncfusion().Grid<Order>("Grid1")
.Caption("Orders")
.Filtering(filter =>
{
filter.FilterDropDownType(FilterDropDownType.SimpleList);
}).Render();
}
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("Grid1")
.ActionMode(ActionMode.JSON)
.Caption("Orders")
.EnablePaging()
.EnableSorting()
.Filtering(filter =>
{
filter.FilterDescriptors(descriptor =>
{
descriptor.Add(c => c.EmployeeID).FilterBy(FilterType.Equals).FilterValue(5);
});
})
.AutoFormat(Skins.Sandune)
.Column( columns => {
columns.Add(p => p.OrderID).HeaderText("Order ID").AllowFilter(false);
columns.Add(p => p.CustomerID).HeaderText("Customer ID");
columns.Add(p => p.EmployeeID).HeaderText("Employee ID"); col
columns.Add(p => p.OrderDate).HeaderText("Order Date");
})
%>
View [cshtml]
@{ Html.Syncfusion().Grid<Order>("Grid1")
.ActionMode(ActionMode.JSON)
.Caption("Orders")
.EnablePaging()
.EnableSorting()
.Filtering(filter =>
{
filter.FilterDescriptors(descriptor =>
{
descriptor.Add(c => c.EmployeeID).FilterBy(FilterType.Equals).FilterValue(5);
});
})
.AutoFormat(Skins.Sandune)
.Column( columns => {
columns.Add(p => p.OrderID).HeaderText("Order ID").AllowFilter(false);
columns.Add(p => p.CustomerID).HeaderText("Customer ID");
columns.Add(p => p.EmployeeID).HeaderText("Employee ID"); col
columns.Add(p => p.OrderDate).HeaderText("Order Date");
}).Render();
}
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("Grid1","GridModel", column
s => {
columns.Add(p => p.OrderID)
columns.Add(p => p.CustomerID)
columns.Add(p => p.EmployeeID);
columns.Add(P => P.ShipCountry);
columns.Add(p => p.OrderDate).Format("{0:dd-MM-yyyy}");
})%>
View [cshtml]
[Controller]
public ActionResult Index()
{
GridPropertiesModel<Order> gridModel = new
GridPropertiesModel<Order>()
{
Caption = "Orders",
AutoFormat = Syncfusion.Mvc.Shared.Skins.Sandune,
AllowFiltering = true,
ActionMode = ActionMode.JSON
};
ViewData["GridModel"] = gridModel;
return View();
}
6. To work with filtering actions, create a Post method for Index actions and bind the data
source to the grid as given in the below code.
Controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new NorthwindDataContext().Orders.ToList();
return data.GridJSONActions<Order>();
}
To enable or disable the filtering options for individual columns, use the
AllowFilter(bool) method in column mapping.
View[ASPX]
<%=Html.Syncfusion().Grid<Order>("FilteringGrid","GridModel", columns =
> {
columns.Add(p => p.OrderID).HeaderText("Order ID").AllowFil
ter(false);
columns.Add(p => p.CustomerID).HeaderText("Customer ID");
columns.Add(p => p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship Country");
columns.Add(p => p.OrderDate).HeaderText("Order Date").Form
at("{0:dd-MM-yyyy}");
})%>
View [cshtml]
@( Html.Syncfusion().Grid<Order>("FilteringGrid","GridModel",
columns => {
columns.Add(p => p.OrderID).HeaderText("Order ID").AllowFil
ter(false);
columns.Add(p => p.CustomerID).HeaderText("Customer ID");
columns.Add(p => p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship Country");
columns.Add(p => p.OrderDate).HeaderText("Order Date").Form
at("{0:dd-MM-yyyy}");
}))
To render the filter menu in a simple drop-down list, use the FilterDropDownType
property.
[Controller]
To render the grid with the initial filtering, add filter conditions using the FilterDescriptors
property.
[Controller]
To render the grid with initial filtering, add the filter conditions using the FilterDescriptors
property.
[Controller]
ActionMode = ActionMode.JSON,
Caption = "Orders",
AllowFiltering = true,
AutoFormat = Skins.Sandune
};
ViewData["GridModel"] = gridModel;
return View();
}
Sample Link
To view the samples, follow the steps below:
1. Open the Grid sample browser from the dashboard (Refer to the Samples and Location
chapter).
2. Navigate to Grid.MVC > Filtering > JSON Mode
The filter bar feature allows the grid to filter records with different expressions depending upon
the column type. The filter bar will be displayed at the top of the grid below the header row.
The filter bar allows you to filter expressions and get the data you want to filter by manually
entering data, unlike the default filter. This allows you to filter the values you want, with ease.
The following figure gives you a basic idea of the appearance of the filter bar in the MVC grid:
Figure 74: Grid with Filter Bar and Filter Status Message Bar
4.5.3.1 Properties
Type of Value it
Property Description Dependencies
property accepts
Type of Value it
Property Description Dependencies
property accepts
mode. enum FilterBar
This property
specifies whether Depends on FilterMode—
FilterBarMod OnEnter
the filter data will
FilterBarMode be rendered e enum Immediate If FilterMode is set to
immediately or FilterBar, then FilterBarMode
after pressing the is activated.
ENTER key.
Depends on
ShowFilterBarStatusMessag
e—
FilterStatusBa Specifies the
rWidth Any integer Only if
width of the filter int
value ShowFilterBarStatusMessag
status bar.
e is enabled,
FilterStatusBarWidth is
enabled.
Examples
Filter token (should be used as Description Used at
shown below)
*value
Examples
Filter token (should be used as Description Used at
shown below)
>value or <=value
>value or <value
Or (or) || Between Numeric & DateTime
>=value || <value
>=value || <=value
0 0 Equals Boolean
1 1 Equals Boolean
4. To enable the filter bar filtering mode, set the FilterMode enum property to FilterBar. The
filter bar status message can be viewed by enabling the property
ShowFilterStatusMessage. The filter bar mode can be set to Immediate or OnEnter by
setting the enum property FilterBarMode.
The ASPX and Razor codes given below will help you customize the grid:
View[ASPX]
<%=Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.Column(column =>
{
column.Add(p =>
p.OrderID).HeaderText("Order ID").AllowFilter(false);
column.Add(p =>
p.CustomerID).HeaderText("Customer ID");
column.Add(p =>
p.ShipCountry).HeaderText("Ship Country");
column.Add(p =>
p.OrderDate).HeaderText("Order Date").Format("{OrderDate:dd/MM/yyyy}");
column.Add(p =>
p.Freight).HeaderText("Price").Format("{0:c}");
})
.EnablePaging()
.EnableSorting()
.AutoFormat(Skins.Sandune).EnableGrouping()
.Filtering(filter =>
{
filter.AllowFiltering(true);
// Specifies the filter mode.
filter.FilterMode(FilterMode.FilterBar);
// Specifies the filter bar
mode.
filter.FilterBarMode(FilterBarMode.Immediate);
// Specifies whether the filter
status message will be shown.
filter.ShowFilterStatusMessage(true);
})
%>
View[cshtml]
@{Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.Column(column =>
{
column.Add(p =>
p.OrderID).HeaderText("Order ID").AllowFilter(false);
column.Add(p =>
p.CustomerID).HeaderText("Customer ID");
column.Add(p =>
p.ShipCountry).HeaderText("Ship Country");
column.Add(p =>
p.OrderDate).HeaderText("Order Date").Format("{OrderDate:dd/MM/yyyy}");
column.Add(p =>
p.Freight).HeaderText("Price").Format("{0:c}");
})
.EnablePaging()
.EnableSorting()
.AutoFormat(Skins.Sandune).EnableGrouping()
.Filtering(filter =>
{
filter.AllowFiltering(true);
// Specifies the filter mode.
filter.FilterMode(FilterMode.FilterBar);
// Specifies the filter bar
mode.
filter.FilterBarMode(FilterBarMode.Immediate);
// Specifies whether the filter
status message will be shown.
filter.ShowFilterStatusMessage(true);
})
.Render();
Controller
/// <summary>
/// Used for rendering the grid initially.
/// </summary>
/// <returns>View page; it displays the grid.</returns>
public ActionResult Index()
{
IEnumerable data = new
NorthwindDataContext().Orders.Take(200).ToList();
return View(data);
6. In order to work with filter actions, create a Post method for Index actions and bind the
data source to the grid as shown in the following code:
Controller
<summary>
/// Paging, editing, and filtering requests are mapped to this
method. This method invokes the HtmlActionResult
/// from the grid and the required response is generated.
/// </summary>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new
NorthwindDataContext().Orders.Take(200).ToList();
return data.GridActions<Order>();
7. Run the application and use the filtering tokens in the filter bar to filter the data table. The
valid tokens are listed in the filter token table.
The following image is an output sample of a filter bar implemented in a grid:
3. Add the following code in the Index.aspx file to create the Grid control in the view.
View[ASPX]
View[cshtml]
Controller
/// <summary>
/// Used for rendering the grid initially.
/// </summary>
/// <returns>View page; it displays the grid.</returns>
public ActionResult Index()
{
GridPropertiesModel<Order> gridModel = new
GridPropertiesModel<Order>()
{
DataSource = new
NorthwindDataContext().Orders.Take(200).ToList(),
Caption = "Orders",
AllowPaging = true,
AllowSorting = true,
AllowFiltering = true,
AutoFormat = Skins.Sandune
};
gridModel.Filters.FilterMode = FilterMode.FilterBar;
gridModel.Filters.FilterBarMode = FilterBarMode.Immediate;
gridModel.Filters.ShowFilterStatusMessage = true;
ViewData["GridModel"] = gridModel;
return View();
}
/// <summary>
/// Paging, editing, and filtering requests are mapped to this
method. This method invokes the HtmlActionResult
/// from the grid and the required response is generated.
/// </summary>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new
NorthwindDataContext().Orders.Take(200).ToList();
return data.GridActions<Order>();
6. Run the application and use the filtering tokens in the filter bar to filter the data table. The
valid tokens are listed in the filter token table.
18. The following figure is an output sample of a filter bar implemented in a grid.
4.5.3.4 How to Filter Data Using Filter Tokens in the Filter Bar
Filter tokens are the symbols that are used in filter expressions to filter data as you require.
Refer to Filter Tokens to learn more about them.
Use these filter tokens in the filter bar as necessary to filter data according to your needs.
Sample Link
To view the samples, follow the steps below:
1. Open the Grid sample browser from the dashboard (Refer to the Samples and Location
chapter).
2. Navigate to Grid.MVC > Filtering > FilterBar
4.5.4 Searching
The searching feature is used to search for text in the data displayed in the grid. A Search text
box and Search button can be configured through toolbar items. This works similar to the Find
functionality in text editor applications. Users can effectively use this feature for finding the
searched strings.
View [cshtml]
@{ Html.Syncfusion().Grid<Order>("SearchingGrid")
.Datasource(Model)
.Caption("Orders")
.EnablePaging()
.AutoFormat(Skins.Sandune)
.Column( columns => {
columns.Add(p => p.OrderID).HeaderText("Order
ID");
columns.Add(p =>
p.CustomerID).HeaderText("Customer ID");
columns.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship
Country");
columns.Add(p => p.ShipCity).HeaderText("Ship
City");
}).Render(); }
4. To activate the search feature in the view, set the AllowSearching property to True.
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("SearchingGrid")
.Datasource(Model)
.Caption("Orders")
.AllowSearching(true)
.EnablePaging()
.AutoFormat(Skins.Sandune)
.Column( columns => {
columns.Add(p => p.OrderID).HeaderText("Order
ID");
columns.Add(p =>
p.CustomerID).HeaderText("Customer ID");
columns.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship
Country");
columns.Add(p => p.ShipCity).HeaderText("Ship
City");
})%>
View [cshtml]
@( Html.Syncfusion().Grid<Order>("SearchingGrid")
.Datasource(Model)
.Caption("Orders")
.AllowSearching(true)
.EnablePaging()
.AutoFormat(Skins.Sandune)
.Column( columns => {
columns.Add(p => p.OrderID).HeaderText("Order
ID");
columns.Add(p =>
p.CustomerID).HeaderText("Customer ID");
columns.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship
Country");
columns.Add(p => p.ShipCity).HeaderText("Ship
City");
}) )
5. If you want to enable or disable the search options for individual columns, use the
AllowSearching(bool) method in column mapping.
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("SearchingGrid")
.Datasource(Model)
.Caption("Orders")
.EnablePaging()
.EnableSorting()
.EnableFiltering()
.AutoFormat(Skins.Sandune)
.Column( columns => {
View [cshtml]
@{ Html.Syncfusion().Grid<Order>("SearchingGrid")
.Datasource(Model)
.Caption("Orders")
.EnablePaging()
.EnableSorting()
.EnableFiltering()
.AutoFormat(Skins.Sandune)
.Column( columns => {
columns.Add(p => p.OrderID).HeaderText("Order ID").
AllowSearching(false);
columns.Add(p => p.CustomerID).HeaderText("Customer ID");
columns.Add(p => p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship Country")
;
columns.Add(p => p.OrderDate).HeaderText("Order Date");
}).Render();
}
Controller
/// <summary>
/// Used to bind the grid.
/// </summary>
/// <returns>View page; it displays the grid.</returns>
public ActionResult Index()
{
var data = new NorthwindDataContext().Orders;
return View(data);
}
7. In order to work with searching actions, create a Post method for Index actions and
bind the data source to the grid as shown in the following code.
Controller
/// <summary>
/// Paging/sorting requests are mapped to this method. This
method invokes the HtmlActionResult
/// from the grid. Required response is generated.
/// </summary>
/// <param name="args">Contains paging properties.</param>
/// <returns>
/// HtmlActionResult returns the data displayed on the grid.
/// </returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
View[cshtml]
If you want to enable or disable the filtering options for individual columns, then use the
AllowSearching(bool) method in column mapping.
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("SearchingGrid","GridModel", columns =
> {
columns.Add(p => p.OrderID).HeaderText("Order ID").AllowSea
rching(false);
columns.Add(p => p.CustomerID).HeaderText("Customer ID");
columns.Add(p => p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship Country");
columns.Add(p => p.OrderDate).HeaderText("Order Date").Form
at("{0:dd-MM-yyyy}");
})%>
View [cshtml]
@(Html.Syncfusion().Grid<Order>("SearchingGrid","GridModel",
columns => {
columns.Add(p => p.OrderID).HeaderText("Order ID").AllowSea
rching(false);
columns.Add(p => p.CustomerID).HeaderText("Customer ID");
columns.Add(p => p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship Country");
columns.Add(p => p.OrderDate).HeaderText("Order Date").Form
at("{0:dd-MM-yyyy}");
}))
Controller
Essential Grid allows searching records through grid toolbar items. In this example,
Search button has been added as toolbar items in the code sample displayed below.
Controller
// Configure the toolbar.
ToolbarSettings toolbar = new ToolbarSettings();
toolbar.Enable = true;
Sample Link
To view the samples, follow the steps below:
1. Open the Essential Grid sample browser from the dashboard. (Refer to the Samples and
Location chapter)
2. Navigate to Grid.MVC > Filtering > Searching
4.6 Grouping
4.6.1 Server Mode
Grouping is defined as the act or process of consolidating grid data into groups. Grouping allows
the categorization of records based on specified columns. You can easily group by a particular
column by simply dragging the column to the upper portion of the grid. The grid data is
automatically grouped when you drop a particular column. You are also able to expand a grouped
record by clicking the icon beside the grouped record.
The Grid control has the following properties and methods which enable and control the grouping
feature.
Properties
feature.
Default value is
False.
Methods
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.EnablePaging()
.EnableSorting()
.EnableGrouping()
View [cshtml]
@{ Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.EnablePaging()
.EnableSorting()
.EnableGrouping()
.Column( columns => {
columns.Add(p => p.OrderID).HeaderText("Order
ID");
columns.Add(p =>
p.CustomerID).HeaderText("Customer ID");
columns.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship
Country");
columns.Add(p => p.ShipCity).HeaderText("Ship
City");
}).Render();
}
4. To enable the grouping feature for your grid you should use the EnableGrouping() method.
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.EnablePaging()
.EnableSorting()
.EnableGrouping()
.Column( columns => {
View [cshtml]
@{ Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.EnablePaging()
.EnableSorting()
.EnableGrouping()
.Column( columns => {
columns.Add(p => p.OrderID).HeaderText("Order
ID");
columns.Add(p =>
p.CustomerID).HeaderText("Customer ID");
columns.Add(p => p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship
Country");
columns.Add(p => p.ShipCity).HeaderText("Ship
City");
}).Render();
}
Controller
/// <summary>
/// Used to bind the grid.
/// </summary>
/// <returns>View page; it displays the grid.</returns>
public ActionResult Index()
{
var data = new NorthwindDataContext().Orders;
return View(data);
}
6. In order to work with sorting actions, create a Post method for Index actions and bind the
data source to the grid as shown in the following code sample.
Controller
/// <summary>
/// Paging and sorting requests are mapped to this method. This
method invokes the HtmlActionResult
/// from the grid. The required response is generated.
/// </summary>
/// <param name="args">Contains paging properties. </param>
/// <returns>
/// HtmlActionResult returns the data displayed on the grid.
/// </returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new NorthwindDataContext().Orders;
return data.GridActions<Order>();
}
Drag and drop any columns in the group drop area. After grouping, the grid will appear as shown
below.
<%=Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.EnablePaging()
.EnableSorting()
.Grouping( group => group.AllowGrouping(true))
%>
1. If you want to render the grid with the initial grouping, use
GroupDescriptors() method.
<%=Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.EnablePaging()
.EnableSorting()
.Grouping(group =>
{
group.GroupDescriptors(cols => cols.Add(c =>
c.CustomerID));
})
%>
View [cshtml]
@{ Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.EnablePaging()
.EnableSorting()
.Grouping( group => group.AllowGrouping(true))
}
2. If you want to render the grid with the initial grouping, use
GroupDescriptors() method.
@{ Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.EnablePaging()
.EnableSorting()
.Grouping(group =>
{
group.GroupDescriptors(cols => cols.Add(c =>
c.CustomerID));
}).Render();
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("GroupingGrid","GridModel"
, columns => {
columns.Add(p => p.OrderID).HeaderText("Order
ID");
columns.Add(p =>
p.CustomerID).HeaderText("Customer ID");
columns.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
columns.Add(P =>
P.ShipCountry).HeaderText("Ship Country");
columns.Add(p => p.ShipCity).HeaderText("Ship
City");
})%>
View [cshtml]
@( Html.Syncfusion().Grid<Order>("GroupingGrid","GridModel", columns =>
{
columns.Add(p => p.OrderID).HeaderText("Order
ID");
columns.Add(p =>
p.CustomerID).HeaderText("Customer ID");
columns.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
columns.Add(P =>
P.ShipCountry).HeaderText("Ship Country");
columns.Add(p => p.ShipCity).HeaderText("Ship
City");
}))
Controller
5. In order to work with grouping actions, create a Post method for Index actions and bind the
data source to the grid as done in the following code sample.
Controller
/// <summary>
/// Paging, sorting, and grouping requests are mapped to this
method. This method invokes the HtmlActionResult
/// from the grid. The required response is generated.
/// </summary>
/// <param name="args">Contains paging properties. </param>
/// <returns>
/// HtmlActionResult returns the data displayed on the grid.
/// </returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new NorthwindDataContext().Orders;
return data.GridActions<Order>();
}
Drag and drop any columns in the group drop area. After grouping, the grid will appear as shown
below.
If you want to render the grid with initial grouping, use the GroupDescriptors property.
/// <summary>
/// Used for rendering the grid initially.
/// </summary>
/// <returns>View page; it displays the grid.</returns>
public ActionResult Index()
{
GridPropertiesModel<Order> gridModel = new
GridPropertiesModel<Order>()
{
DataSource = new NorthwindDataContext().Orders,
Caption = "Orders",
AllowPaging = true,
AllowSorting = true,
AllowMultiSorting = true,
AllowGrouping = true,
AutoFormat = Skins.Sandune
};
gridModel.GroupDescriptors.Add("CustomerID");
ViewData["GridModel"] = gridModel;
return View();
}
Sample Link
To view the samples, follow the steps below:
1. Open the Grid sample browser from the dashboard (Refer to the Samples and Location
chapter).
2. Navigate to Grid.MVC > Grouping > Server Mode
1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. Create the Grid control in the view and configure its properties.
4. Set the JSON action mode using the ActionMode method.
5. To enable the grouping feature for your grid you should use the EnableGrouping() method.
View [ASPX]
<%= Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.ActionMode(ActionMode.JSON)
.Caption("Orders")
.EnablePaging()
.EnableSorting()
.EnableGrouping()
.Column( columns => {
columns.Add(p => p.OrderID).HeaderText("Order
ID");
columns.Add(p =>
p.CustomerID).HeaderText("Customer ID");
columns.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship
Country");
columns.Add(p => p.ShipCity).HeaderText("Ship
City");
}) %>
View [cshtml]
@{ Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.ActionMode(ActionMode.JSON)
.EnablePaging()
.EnableSorting()
.EnableGrouping()
.Column( columns => {
columns.Add(p => p.OrderID).HeaderText("Order
ID");
columns.Add(p =>
p.CustomerID).HeaderText("Customer ID");
columns.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship
Country");
columns.Add(p => p.ShipCity).HeaderText("Ship
City");
}).Render();
}
Controller
7. In order to work with grouping actions, create a Post method for Index actions and bind the
data source to the grid as shown in the following code sample.
Controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new NorthwindDataContext().Orders.ToList();
return data.GridJSONActions<Order>();
}
Drag and drop any columns in the group drop area. After grouping, the grid will appear as shown
below.
<%=Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.ActionMode(ActionMode.JSON)
.EnablePaging()
.EnableSorting()
.Grouping( group => group.AllowGrouping(true))
%>
1. If you want to render the grid with the initial grouping, use
GroupDescriptors() method.
<%=Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.ActionMode(ActionMode.JSON)
.EnablePaging()
.EnableSorting()
.Grouping(group =>
{
group.GroupDescriptors(cols => cols.Add(c =>
c.CustomerID));
})
%>
View [cshtml]
@{ Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.ActionMode(ActionMode.JSON)
.EnablePaging()
.EnableSorting()
.Grouping( group => group.AllowGrouping(true))
}
2. If you want to render the grid with the initial grouping, use
GroupDescriptors() method.
@{ Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.ActionMode(ActionMode.JSON)
.EnablePaging()
.EnableSorting()
.Grouping(group =>
{
group.GroupDescriptors(cols => cols.Add(c =>
c.CustomerID));
}).Render();
View [cshtml]
ActionMode=ActionMode.JSON,
AllowSorting=true,
AllowMultiSorting=true,
AllowGrouping=true,
AutoFormat=Skins.Sandune
};
ViewData["GridModel"] = gridModel; // Pass the model from
controller to view using ViewData.
return View();
}
5. In order to work with grouping actions, create a Post method for Index actions and bind the
data source to the grid as done in the following code sample.
Controller
/// <summary>
/// Paging, sorting, and grouping requests are mapped to this
method. This method invokes the HtmlActionResult
/// from the grid. The required response is generated.
/// </summary>
/// <param name="args">Contains paging properties. </param>
/// <returns>
/// HtmlActionResult returns the data displayed on the grid.
/// </returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new NorthwindDataContext().Orders;
return data. GridJSONActions<Order>();
}
Drag and drop any columns in the group drop area. After grouping, the grid will appear as shown
below.
If you want to render the grid with initial grouping, use the GroupDescriptors property.
/// <summary>
/// Used for rendering the grid initially.
/// </summary>
/// <returns>View page; it displays the grid.</returns>
public ActionResult Index()
{
GridPropertiesModel<Order> gridModel = new
GridPropertiesModel<Order>()
{
DataSource = new NorthwindDataContext().Orders,
Caption = "Orders",
AllowPaging = true,
AllowSorting = true,
ActionMode=ActionMode.JSON,
AllowMultiSorting = true,
AllowGrouping = true,
AutoFormat = Skins.Sandune
};
ViewData["GridModel"] = gridModel;
return View();
}
Sample Link
To view the samples, follow the steps below:
1. Open the Grid sample browser from the dashboard (Refer to the Samples and Location
chapter).
2. Navigate to Grid.MVC > Grouping > JSON Mode
4.7 Editing
Essential Grid has built-in support for editing grid content. This can be achieved by defining a
GridEditing class for the grid. Using this class, you can specify the action mappers for insert,
edit, update, delete, and cancel requests.
Key Features
The key features of editing are as follows:
Allows nine modes of editing, such as inline row editing, inline form editing, inline custom
template form editing, dialog editing, dialog custom template form editing, external form
editing, external custom template form editing, auto excel editing, and manual editing.
Enables MVC 4.0 client validation.
Provides toolbar support for editing records.
Properties
Any other
dependenc
Type of
Property Description Value it accepts ies/sub-
property
properties
associated
Editing Gets or sets
the editing
properties for Class NA NA
the Grid
control.
AllowNew Used to
enable or
disable the
bool True/False NA
insert action in
the editing
mode.
AllowEdit Used to
enable or
disable the
bool True/False NA
edit action in
the editing
mode.
AllowDelete Used to
enable or
disable the
bool True/False NA
delete action
in the editing
mode.
Any other
dependenc
Type of
Property Description Value it accepts ies/sub-
property
properties
associated
the action
mapper for the
insert actions.
GridEditMode.ManualExcel
GridEditMode.Normal
Enable Used to
enable or
disable the Bool True/False NA
toolbar in grid.
Any other
dependenc
Type of
Property Description Value it accepts ies/sub-
property
properties
associated
Items Used to add
List<Toolba
the items to Any toolbar items NA
rOptions>
grid toolbars.
The following table illustrates the default CellEditTypes and their corresponding controls for
specific data types.
Methods
[Site.Master]
<head runat="server">
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server"
/></title>
………
<script src="<%=
Url.Content("~/Scripts/MicrosoftMvcValidation.debug.js") %>"
type="text/javascript"></script>
</head>
[_Layout.cshtml]
<head runat="server">
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server"
/></title>
………
<script
src="@Url.Content("~/Scripts/MicrosoftMvcValidation.debug.js ")"
type="text/javascript"></script>
</head>
Note: Add the following script files when the UnobtrusiveJavaScriptEnabled is true in
web.config file.
[Web.config]
<configuration>
<appSettings>
<add key='UnobtrusiveJavaScriptEnabled' value='true'/>
</appSettings>
[_Layout.cshtml]
<head>
. . . .
. . . .
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")"
type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")"
type="text/javascript"></script>
<script
src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"
type="text/javascript"></script>
</head>
[Site.Master]
<head runat="server">
. . . .
. . . .
<script src="<%=Url.Content("~/Scripts/jquery.unobtrusive-
ajax.min.js")%>" type="text/javascript"></script>
<script src="<%=Url.Content("~/Scripts/jquery.validate.min.js")%>"
type="text/javascript"></script>
<script
src="<%=Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")%
>" type="text/javascript"></script>
</head>
2. Create a model in the application. Refer to How to>Adding a Model to the Application and
Editing>EditableOrder Class.
3. Create a strongly typed view. Refer to How to>Strongly Typed View.
4. In the view, use the Model property in the Datasource() to bind the data source.
View [ASPX]
<%=Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model)
.Caption("Orders")
.Column(column =>
{
column.Add(p =>
p.OrderID).HeaderText("Order ID");
column.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
column.Add(p =>
p.CustomerID).HeaderText("Customer ID");
column.Add(p =>
p.ShipCountry).HeaderText("Ship Country");
column.Add(p =>
p.OrderDate).HeaderText("Order
Date").Format("{OrderDate:MM/dd/yyyy}");
column.Add(p =>
p.Freight).HeaderText("Freight");
})
.EnablePaging()
.EnableSorting()
.EnableGrouping()
%>
View [cshtml]
@{ Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model)
.Caption("Orders")
.Column(column =>
{
column.Add(p =>
p.OrderID).HeaderText("Order ID");
column.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
column.Add(p =>
p.CustomerID).HeaderText("Customer ID");
column.Add(p =>
p.ShipCountry).HeaderText("Ship Country");
column.Add(p =>
p.OrderDate).HeaderText("Order
Date").Format("{OrderDate:MM/dd/yyyy}");
column.Add(p =>
p.Freight).HeaderText("Freight");
})
.EnablePaging()
.EnableSorting()
.EnableGrouping()
.Render();
5. Enable editing by using the Editing method and configure the editing properties such as
AllowNew, AllowEdit, and AllowDelete, as displayed below.
View [ASPX]
<%=Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model)
.Caption("Orders")
.Editing( edit=>{
edit.AllowEdit(true, "Home/OrderSave")// Specify the
controller and action method which will perform the update action.
.AllowNew(true, "Home/AddOrder")// Specify the
controller and action method which will perform the insert action.
.AllowDelete(true, "Home/DeleteOrder");// Specify
the controller and action method which will perform the delete action.
})
%>
View [cshtml]
@{ Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model)
.Caption("Orders")
.Editing( edit=>{
edit.AllowEdit(true, "Home/OrderSave")// Specify the
controller and action method which will perform the update action.
.AllowNew(true, "Home/AddOrder")// Specify the
controller and action method which will perform the insert action.
.AllowDelete(true, "Home/DeleteOrder");// Specify
the controller and action method which will perform the delete action.
}).Render();
Note: If you want to specify the URL in the AllowEdit property itself means, specify the controller
and the corresponding action name as a URL. If you using the Mappers property then there is no
need to specify the controller name.
6. Grid allows adding new records through grid toolbar items. In this example, the AddNew,
Edit, Delete, Save, and Cancel buttons have been added as toolbar items in the following
code sample.
View [ASPX]
<%=Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model)
.Caption("Orders")
.ToolBar(tools =>
{
tools.Add(GridToolBarItems.AddNew)// Toolbar
item for inserting record.
.Add(GridToolBarItems.Edit)// Toolbar
item for editing record.
.Add(GridToolBarItems.Delete)// Toolbar
item for deleting record.
.Add(GridToolBarItems.Update)// Toolbar
item for saving changes.
.Add(GridToolBarItems.Cancel);// Toolbar
item for Cancel request.
})
%>
View [cshtml]
@{ Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model)
.Caption("Orders")
.ToolBar(tools =>
{
tools.Add(GridToolBarItems.AddNew)// Toolbar
item for insert record.
.Add(GridToolBarItems.Edit)// Toolbar
item for editing record.
.Add(GridToolBarItems.Delete)// Toolbar
item for deleting record.
.Add(GridToolBarItems.Update)// Toolbar
item for saving changes.
.Add(GridToolBarItems.Cancel);// Toolbar
item for Cancel request.
}).Render();
7. Specify the Primary property which uniquely identifies the grid record.
View [ASPX]
<%=Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model)
.Caption("Orders")
.Editing( edit=>{
edit.PrimaryKey(key => key.Add(p =>
p.OrderID)); // Add primary key to primary key collections.
})
%>
View [cshtml]
@{ Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model)
.Caption("Orders")
.Editing( edit=>{
edit.PrimaryKey(key => key.Add(p =>
p.OrderID)); // Add primary key to primary key collections.
}).Render();
}
You can also add multiple primary keys. The following code illustrates this:
View[Aspx]
<%=Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model)
.Caption("Orders")
.Editing( edit=>{
edit.PrimaryKey(key => key.Add(p =>
p.OrderID).Add(p => p.EmployeeID).Add(p => p.CustomerID)); // Add
primary key to primary key collections.
})
%>
View [ASPX]
<%=Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model)
.Caption("Orders")
.Column(column =>
.Editing( edit=>{
edit.EditMode(GridEditMode.Normal);//
specify the edit mode
})
%>
View [cshtml]
@{ Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model)
.Caption("Orders")
.Column(column =>
.Editing( edit=>{
edit.EditMode(GridEditMode.Normal);//
specify the edit mode
}).Render();
}
9. In the controller, create a method to add new records to the grid as displayed below. In this
example, the repository method Add() is being created to insert records to the database.
Refer to the repository action method displayed below.
Controller
/// <summary>
/// Used to insert the record into database and refresh the
grid.
/// </summary>
/// <param name="ord">Editable order</param>
/// <returns>HtmlActionResult returns the data displayed on the
grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddOrder(EditableOrder ord)
{
// Repository action method Add is used to insert records in
the data source.
OrderRepository.Add(ord);
grid.
var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}
10. In the controller, create a method to save changes, as displayed below. In this example, the
repository method Update() is used to update records to the data source.
Controller
/// Used to insert the record into database and refresh the grid.
/// </summary>
/// <param name="ord">Editable order</param>
/// <returns>HtmlActionResult which returns data displayed on
the grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult OrderSave(EditableOrder ord)
{
// Repository action method Update is used to update the
records in the data source.
OrderRepository.Update(ord);
11. In the controller, create a method to delete the records from the database as displayed
below. In this example, the repository action Delete() will delete the record from the data
source.
Controller
/// <summary>
/// Used for deleting the records from the data source and
refreshing the grid.
/// </summary>
/// <param name="OrderID">Primary key values</param>
/// <returns>HtmlActionResult returns the data displayed on the
grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult DeleteOrder(int OrderID)
{
// Repoistory action Delete() deletes the given primary
value record from the data source.
OrderRepository.Delete(OrderID);
12. Run the application. The grid will appear as displayed below.
Figure 87: Grid with Toolbar Options for Editing, Inserting, and Deleting
The following screenshot shows the default editing controls such as NumericTextBox for integer
types (namely “Employee ID”), NumericTextbox for decimal types (namely “Freight”), DatePicker
for date-time types (namely “Order Date”).
Essential Grid provides three modes for editing. To set the edit form mode of editing, use
the EditMode() method.
View [ASPX]
<%=Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model)
.Caption("Orders")
.Editing( edit=>{
edit.EditMode(GridEditMode.InlineForm);
})
%>
View [cshtml]
@{ Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model)
.Caption("Orders")
.Editing( edit=>{
edit.EditMode(GridEditMode.InlineForm);
}).Render();
}
If you configure the edit mode as InlineForm, the grid will appear in the editing mode displayed
below.
1. If you want to use the TemplateForm mode, follow the steps displayed below.
View [ASCX]
<fieldset>
<legend>Fields</legend>
<div class="tablediv">
<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">
<%= Html.Syncfusion().LabelFor(model
=> model.OrderID) %>
</div>
<div class="editor-field">
<%=
Html.Syncfusion().TextBoxFor(model => model.OrderID) %>
<%=
Html.Syncfusion().ValidationMessageFor(model =>
model.OrderID) %>
</div>
</div>
<div class="celldiv" style="height: auto">
<div class="editor-label">
<%= Html.Syncfusion().LabelFor(model
=> model.CustomerID) %>
</div>
<div class="editor-field">
<%=
Html.Syncfusion().TextBoxFor(model => model.CustomerID)
%>
<%=
Html.Syncfusion().ValidationMessageFor(model =>
model.CustomerID) %>
</div>
</div>
</div>
<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">
<%= Html.Syncfusion().LabelFor(model
=> model.EmployeeID) %>
</div>
<div class="editor-field">
<%=
Html.Syncfusion().TextBoxFor(model => model.EmployeeID)
%>
<%=
Html.Syncfusion().ValidationMessageFor(model =>
model.EmployeeID) %>
</div>
</div>
<div class="celldiv" style="height: auto">
<div class="editor-label">
<%= Html.Syncfusion().LabelFor(model
=> model.ShipName) %>
</div>
<div class="editor-field">
<%=
Html.Syncfusion().TextBoxFor(model => model.ShipName) %>
<%=
Html.Syncfusion().ValidationMessageFor(model =>
model.ShipName) %>
</div>
</div>
</div>
<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">
<%= Html.Syncfusion().LabelFor(model
=> model.ShipAddress) %>
</div>
<div class="editor-field">
<%=
Html.Syncfusion().TextBoxFor(model => model.ShipAddress)
%>
<%=
Html.Syncfusion().ValidationMessageFor(model =>
model.ShipAddress) %>
</div>
</div>
<div class="celldiv" style="height: auto">
<div class="editor-label">
<%= Html.Syncfusion().LabelFor(model
=> model.ShipCity) %>
</div>
<div class="editor-field">
<%=
Html.Syncfusion().TextBoxFor(model => model.ShipCity) %>
<%=
Html.Syncfusion().ValidationMessageFor(model =>
model.ShipCity) %>
</div>
</div>
</div>
<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">
<%= Html.Syncfusion().LabelFor(model
=> model.ShipRegion) %>
</div>
<div class="editor-field">
<%=
Html.Syncfusion().TextBoxFor(model => model.ShipRegion)
%>
<%=
Html.Syncfusion().ValidationMessageFor(model =>
model.ShipRegion) %>
</div>
</div>
<div class="celldiv" style="height: auto">
<div class="editor-label">
<%= Html.Syncfusion().LabelFor(model
=> model.ShipCountry) %>
</div>
<div class="editor-field">
<%=
Html.Syncfusion().TextBoxFor(model => model.ShipCountry)
%>
<%=
Html.Syncfusion().ValidationMessageFor(model =>
model.ShipCountry) %>
</div>
</div>
</div>
<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">
<%= Html.Syncfusion().LabelFor(model
=> model.Freight) %>
</div>
<div class="editor-field">
<%=
Html.Syncfusion().TextBoxFor(model => model.Freight) %>
<%=
Html.Syncfusion().ValidationMessageFor(model =>
model.Freight) %>
</div>
</div>
<div class="celldiv" style="height: auto">
<div class="editor-label">
<%= Html.Syncfusion().LabelFor(model
=> model.OrderDate) %>
</div>
<div class="editor-field">
<%=
Html.Syncfusion().TextBoxFor(model => model.OrderDate,
String.Format("{0:g}", Model.OrderDate)) %>
<%=
Html.Syncfusion().ValidationMessageFor(model =>
model.OrderDate) %>
</div>
</div>
</div>
</div>
</fieldset>
View [Razor]
<fieldset>
<legend>Fields</legend>
<div class="tablediv">
<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model => model.OrderID)
</div>
<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model =>
model.OrderID)
@Html.Syncfusion().ValidationMessageFor(model =>
model.OrderID)
</div>
</div>
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model =>
model.CustomerID)
</div>
<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model =>
model.CustomerID)
@Html.Syncfusion().ValidationMessageFor(model =>
model.CustomerID)
</div>
</div>
</div>
<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model =>
model.EmployeeID)
</div>
<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model =>
model.EmployeeID)
@ Html.Syncfusion().ValidationMessageFor(model =>
model.EmployeeID)
</div>
</div>
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model =>
model.ShipName)
</div>
<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model =>
model.ShipName)
@Html.Syncfusion().ValidationMessageFor(model =>
model.ShipName)
</div>
</div>
</div>
<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model =>
model.ShipAddress)
</div>
<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model =>
model.ShipAddress)
@Html.Syncfusion().ValidationMessageFor(model =>
model.ShipAddress)
</div>
</div>
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model => model.ShipCity)
</div>
<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model =>
model.ShipCity)
@ Html.Syncfusion().ValidationMessageFor(model =>
model.ShipCity)
</div>
</div>
</div>
<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model =>
model.ShipRegion)
</div>
<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model =>
model.ShipRegion)
@ Html.Syncfusion().ValidationMessageFor(model =>
model.ShipRegion)
</div>
</div>
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model =>
model.ShipCountry)
</div>
<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model
=>model.ShipCountry)
@Html.Syncfusion().ValidationMessageFor(model =>
model.ShipCountry)
</div>
</div>
</div>
<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model => model.Freight)
</div>
<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model =>
model.Freight)
@Html.Syncfusion().ValidationMessageFor(model =>
model.Freight)
</div>
</div>
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model =>
model.OrderDate)
</div>
<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model =>
model.OrderDate,String.Format("{0:g}", Model.OrderDate))
@Html.Syncfusion().ValidationMessageFor(model =>
model.OrderDate)
</div>
</div>
</div>
</div>
</fieldset>
Note: Don’t specify the form in the template. The <fieldset> tag is required to surround the
template input fields, otherwise the buttons will not be displayed by the dialog.
Configure the GridEditMode as TemplateForm and specify the partial view which
contains the templates.
View [ASPX]
<%=Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model)
.Caption("Orders")
.Editing( edit=>{
edit.EditMode(GridEditMode.InlineTemplateForm);
edit.FormModeEditorTemplate("OrderEditorTemplate");//
Specify the partial view page which contains the
templates.
})
%>
View [cshtml]
@{ Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model)
.Caption("Orders")
.Editing( edit=>{
edit.EditMode(GridEditMode.InlineTemplateForm);
edit.FormModeEditorTemplate("OrderEditorTemplate");//
Specify the partial view page which contains the
templates.
}).Render();
}
In the InlineTemplateForm mode, you should handle the Insert and Edit actions. To
achieve this, check the RequestType property from PagingParams. If the request type
is either BeginEdit or BeginAddNew, render the template by using the PartialView()
method as displayed below.
/// <summary>
/// Paging/editing Request is mapped to this
method. This method invokes the HtmlActionResult
/// from the grid. Required response is
generated.
/// </summary>
/// <param name="args">Contains paging
properties. </param>
/// <returns>
/// HtmlActionResult returns the data displayed
on the grid.
/// </returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args
,int? OrderID)
{
RequestType currentRequest =
(RequestType)Convert.ToInt32(args.RequestType);
// Check if the current request is edit
request and edit mode is Template form mode. Then call
the PartialView() to render the template.
if (currentRequest == RequestType.BeginEdit)
{
EditableOrder ord =
(EditableOrder)OrderRepository.Select(OrderID);
return
PartialView("OrderEditorTemplate", ord);
}
else if (currentRequest ==
RequestType.BeginAddNew)
{
// Check if the current request is add
new request and edit mode is Template form mode then
call the Partialview() to render the template.
return
If you configure the edit mode as TemplateForm, the grid will appear in the editing mode as
displayed below.
Essential Grid provides support for restricting the editing operations in a column. This can be
done by setting the AllowEditing property of particular columns to False.
1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. Create the Grid control in the view and configure its properties.
4. Set the AllowEditing property of a particular column to False.
View [ASPX]
<%=Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model)
.Caption("Orders")
.Column(column =>
{
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.CustomerID).HeaderText("Customer
ID").AllowEditing(false);
column.Add(p => p.ShipCountry).HeaderText("Ship
Country").AllowEditing(false);
column.Add(p => p.OrderDate).HeaderText("Order
Date").Format("{OrderDate:dd/MM/yyyy}");
column.Add(p => p.Freight).HeaderText("Freight");
})
%>
View [cshtml]
@{ Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model)
.Caption("Orders")
.Column(column =>
{
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.CustomerID).HeaderText("Customer
ID").AllowEditing(false);
column.Add(p => p.ShipCountry).HeaderText("Ship
Country").AllowEditing(false);
column.Add(p => p.OrderDate).HeaderText("Order
Date").Format("{OrderDate:dd/MM/yyyy}");
column.Add(p => p.Freight).HeaderText("Freight");
})
.Render();
}
Note: In the code samples, the “Customer ID” and “Ship Country” columns cannot be editable.
5. Render the view.
Controller
6. Run the application and edit the particular record. The grid will appear as shown below.
The steps to work with the editing feature through GridPropertiesModel are as follows.
1. Add the MicrosoftMvcValidation.debug.js file in the master page.
<head runat="server">
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server"
/></title>
………
<script src="<%=
Url.Content("~/Scripts/MicrosoftMvcValidation.debug.js") %>"
type="text/javascript"></script>
</head>
[_Layout.cshtml]
<head runat="server">
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server"
/></title>
………
<script
src="@Url.Content("~/Scripts/MicrosoftMvcValidation.debug.js ")"
type="text/javascript"></script>
</head>
Note: Add the following script files when the UnobtrusiveJavaScriptEnabled is true in
web.config file.
[Web.config]
<configuration>
<appSettings>
<add key='UnobtrusiveJavaScriptEnabled' value='true'/>
</appSettings>
[_Layout.cshtml]
<head>
. . . .
. . . .
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")"
type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")"
type="text/javascript"></script>
<script
src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"
type="text/javascript"></script>
</head>
[Site.Master]
<head runat="server">
. . . .
. . . .
<script src="<%=Url.Content("~/Scripts/jquery.unobtrusive-
ajax.min.js")%>" type="text/javascript"></script>
<script src="<%=Url.Content("~/Scripts/jquery.validate.min.js")%>"
type="text/javascript"></script>
<script
src="<%=Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")%
>" type="text/javascript"></script>
</head>
2. Create a model in the application. Refer to How to>Adding a Model to the Application and
Editing>EditableOrder Class.
3. Create a strongly typed view (Refer to How to>Strongly Typed View).
4. Add the following code in the Index.aspx file to create the Grid control in the view.
View [ASPX]
<%=Html.Syncfusion().Grid<EditableOrder>("Orders_Grid","GridModel
", column=> {
View [cshtml]
@( Html.Syncfusion().Grid<EditableOrder>("Orders_Grid","GridModel",
column=> {
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.EmployeeID).HeaderText("Employee ID");
column.Add(p => p.CustomerID).HeaderText("Customer ID");
column.Add(p => p.ShipCountry).HeaderText("Ship Country");
column.Add(p => p.OrderDate).HeaderText("Order
Date").Format("{OrderDate:MM/dd/yyyy}");
column.Add(p => p.Freight).HeaderText("Freight");
}))
5. Create a GridPropertiesModel in the Index method and assign the grid properties in the
model.
Controller
6. Enable editing by using the Editing property in the GridPropertiesModel and configure the
editing properties such as AllowNew, AllowEdit, and AllowDelete as displayed below.
Controller
delete actions.
GridEditing edit = new GridEditing() { AllowEdit = true,
AllowDelete = true, AllowNew = true };
Controller
8. Specify the primary property, which uniquely identifies the grid record.
Controller
Essential Grid allows adding new records through grid toolbar items. In this example, AddNew,
Edit, Delete, Save, and Cancel buttons have been added as toolbar items in the code sample
displayed below.
Controller
// Configure the toolbar.
ToolbarSettings toolbar = new ToolbarSettings();
toolbar.Enable = true;
GridToolBarItems.Delete });
model.ToolBar = toolbar;
Note: In our earlier versions, toolbar item collection is of type Dictionary<GridToolBarItems key,
string value>. With the inclusion of custom toolbar item support, we can’t add multiple custom
items. The key will be the same (GridToolBarItems.Custom) for all custom items and so we have
modified the toolbar item collection type as List<ToolbarOptions>.
10. In the controller, create a method to add new records to the grid as displayed below. In this
example, the repository method Add() is being created to insert records to the database.
Refer to the repository action method displayed below.
Controller
/// <summary>
/// Used to insert the record into database and refresh the
grid.
/// </summary>
/// <param name="ord">Editable order.</param>
/// <returns>HtmlActionResult returns the data displayed on the
grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddOrder(EditableOrder ord)
{
// Repository action method Add is used to insert records in
the data source.
OrderRepository.Add(ord);
Note: Refer to the repository action codes in Editing > OrderRepository Class.
11. In the controller, create a method to save changes as displayed below. In this example, the
repository method Update() is used to update records to the data source.
Controller
/// Used to insert the record into database and refresh the grid.
/// </summary>
/// <param name="ord">Editable order</param>
/// <returns>HtmlActionResult returns the data displayed on the
grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult OrderSave(EditableOrder ord)
{
// Repository action method Update is used to update the
records in the data source.
OrderRepository.Update(ord);
12. In the controller, create a method to delete records from the database as displayed below.
In this example, the repository action Delete() will delete the record from the data source.
Controller
/// <summary>
/// Used for deleting records from the data source and
refreshing the grid.
/// </summary>
/// <param name="OrderID">Primary key values.</param>
/// <returns>HtmlActionResult returns the data displayed on the
grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult DeleteOrder(int OrderID)
{
// Repoistory action Delete()deletes the given primary
value record from the data source.
OrderRepository.Delete(OrderID);
13. Run the application. The grid will appear as displayed below.
Figure 96: Grid with Toolbar Options for Editing, Inserting, and Deleting Records
Essential Grid provides three modes for editing. To set the InlineForm edit mode, use the
EditMode property.
Controller
//Create object to grid editing and enable edit, addnew, and
delete actions.
GridEditing edit = new GridEditing() { AllowEdit = true,
AllowDelete = true, AllowNew = true };
//Set the Edit mode.
edit.EditMode = GridEditMode.InlineForm;
If you configure the edit mode as EditForm, the grid will appear in the editing mode as displayed
below.
If you want to use the TemplateForm mode, follow the steps displayed below:
1. Create the template in partial view as displayed below.
View [ASCX]
<fieldset>
<legend>Fields</legend>
<div class="tablediv">
<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">
<%= Html.Syncfusion().LabelFor(model =>
model.OrderID) %>
</div>
<div class="editor-field">
<%= Html.Syncfusion().TextBoxFor(model
</div>
</div>
<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">
<%= Html.Syncfusion().LabelFor(model =>
model.Freight) %>
</div>
<div class="editor-field">
<%= Html.Syncfusion().TextBoxFor(model
=> model.Freight) %>
<%=
Html.Syncfusion().ValidationMessageFor(model =>
model.Freight) %>
</div>
</div>
<div class="celldiv" style="height: auto">
<div class="editor-label">
<%= Html.Syncfusion().LabelFor(model =>
model.OrderDate) %>
</div>
<div class="editor-field">
<%= Html.Syncfusion().TextBoxFor(model
=> model.OrderDate, String.Format("{0:g}",
Model.OrderDate)) %>
<%=
Html.Syncfusion().ValidationMessageFor(model =>
model.OrderDate) %>
</div>
</div>
</div>
</div>
</fieldset>
View [Razor]
<fieldset>
<legend>Fields</legend>
<div class="tablediv">
<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model => model.OrderID)
</div>
<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model =>
model.OrderID)
@Html.Syncfusion().ValidationMessageFor(model =>
model.OrderID)
</div>
</div>
</div>
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model => model.ShipCity)
</div>
<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model =>
model.ShipCity)
@ Html.Syncfusion().ValidationMessageFor(model =>
model.ShipCity)
</div>
</div>
</div>
<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model =>
model.ShipRegion)
</div>
<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model =>
model.ShipRegion)
@ Html.Syncfusion().ValidationMessageFor(model =>
model.ShipRegion)
</div>
</div>
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model =>
model.ShipCountry)
</div>
<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model
=>model.ShipCountry)
@Html.Syncfusion().ValidationMessageFor(model =>
model.ShipCountry)
</div>
</div>
</div>
<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model => model.Freight)
</div>
<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model =>
model.Freight)
@Html.Syncfusion().ValidationMessageFor(model =>
model.Freight)
</div>
</div>
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model =>
model.OrderDate)
</div>
<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model =>
model.OrderDate,String.Format("{0:g}", Model.OrderDate))
@Html.Syncfusion().ValidationMessageFor(model =>
model.OrderDate)
</div>
</div>
</div>
</div>
</fieldset>
Note: Don’t specify the form in the template. The <fieldset> tag is required to surround the
template input fields else the buttons will not be displayed by the dialog.
2. Configure the GridMode as TemplateFormMode and specify the partial view which
contains the templates.
Controller
//Create object to grid editing and enable edit,
addnew and delete actions.
GridEditing edit = new GridEditing() {
AllowEdit = true, AllowDelete = true, AllowNew = true };
3. In the InlineTemplateForm mode, you should handle the Insert action Edit actions. To
achieve this, check the RequestType property from PagingParams. If the request type
is either BeginEdit or BeginAddNew, then render the template by using the
PartialView() method as displayed below.
Controller
/// <summary>
/// The paging/editing request is mapped to this
method. This method invokes the HtmlActionResult
/// from the grid. Required response is generated.
/// </summary>
If you configure the edit mode as TemplateForm, the grid will appear in the editing mode as
displayed below.
[Site.Master]
<head runat="server">
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server"
/></title>
………
<script src="<%=
Url.Content("~/Scripts/MicrosoftMvcValidation.debug.js") %>"
type="text/javascript"></script>
</head>
[_Layout.cshtml]
<head runat="server">
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server"
/></title>
………
<script
src="@Url.Content("~/Scripts/MicrosoftMvcValidation.debug.js ")"
type="text/javascript"></script>
</head>
Note: Add the following script files when the UnobtrusiveJavaScriptEnabled is true in
web.config file.
[Web.config]
<configuration>
<appSettings>
<add key='UnobtrusiveJavaScriptEnabled' value='true'/>
</appSettings>
[_Layout.cshtml]
<head>
. . . .
. . . .
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")"
type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")"
type="text/javascript"></script>
<script
src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"
type="text/javascript"></script>
</head>
[Site.Master]
<head runat="server">
. . . .
. . . .
<script src="<%=Url.Content("~/Scripts/jquery.unobtrusive-
ajax.min.js")%>" type="text/javascript"></script>
<script src="<%=Url.Content("~/Scripts/jquery.validate.min.js")%>"
type="text/javascript"></script>
<script
src="<%=Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")%
>" type="text/javascript"></script>
</head>
2. Create a model in the application (Refer to How to>Adding a Model to the Application).
3. Create a strongly typed view (Refer to How to>Strongly Typed View).
4. Create the Grid control in the view and configure its properties.
5. Set the JSON action mode using the ActionMode method.
6. Enable editing by using the Editing method and configure the editing properties such as
AllowNew, AllowEdit, and Allow Delete as displayed below.
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("Grid1")
.Caption("Orders")
.AutoFormat(Skins.Sandune)
.ActionMode(ActionMode.JSON)
.Editing( edit=>{
edit.AllowEdit(true, "Home/OrderSave")// Specify the
action method which will perform the update action.
.AllowNew(true, "Home/AddOrder")// Specify the
action method which will perform the insert action.
.AllowDelete(true, "Home/DeleteOrder");// Specify
the action method which will perform the delete action.
})
.Column( columns => {
columns.Add(p => p.OrderID);
columns.Add(p => p.CustomerID);
columns.Add(p => p.EmployeeID);
columns.Add(P => P.ShipCountry);
columns.Add(p => p.OrderDate).Format("{0:dd-MM-yyyy}");
})
%>
View [cshtml]
@{ Html.Syncfusion().Grid<Order>("Grid1")
.Caption("Orders")
.AutoFormat(Skins.Sandune)
.ActionMode(ActionMode.JSON)
.Editing( edit=>{
edit.AllowEdit(true, "Home/OrderSave")// Specify the
action method which will perform the update action.
.AllowNew(true, "Home/AddOrder")// Specify the
action method which will perform the insert action.
.AllowDelete(true, "Home/DeleteOrder");// Specify
the action method which will perform the delete action.
})
.Column( columns => {
columns.Add(p => p.OrderID);
columns.Add(p => p.CustomerID);
columns.Add(p => p.EmployeeID);
columns.Add(P => P.ShipCountry);
columns.Add(p => p.OrderDate).Format("{0:dd-MM-yyyy}");
}).Render();
}
Note: If you want to specify the URL in the AllowEdit property itself, specify the controller and
the corresponding action name as a URL. If you are using the Mappers property then there is no
need to specify the controller name.
7. Essential Grid allows adding new records through toolbar items. In this example, AddNew,
Edit, Delete, Save, and Cancel buttons have been added as toolbar items as displayed
below.
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("Grid1")
.Caption("Orders")
.AutoFormat(Skins.Sandune)
.ActionMode(ActionMode.JSON)
.ToolBar(tools =>
{
tools.Add(GridToolBarItems.AddNew)// Toolbar
item for Insert record.
.Add(GridToolBarItems.Edit)// Toolbar
item for Editing record.
.Add(GridToolBarItems.Delete)// Toolbar
item for Deleting record.
.Add(GridToolBarItems.Update)// Toolbar
item for save changes.
.Add(GridToolBarItems.Cancel);// Toolbar
item for Cancel request.
})
%>
View [cshtml]
@{ Html.Syncfusion().Grid<Order>("Grid1")
.Caption("Orders")
.AutoFormat(Skins.Sandune)
.ActionMode(ActionMode.JSON)
.ToolBar(tools =>
{
tools.Add(GridToolBarItems.AddNew)// Toolbar
item for Insert record.
.Add(GridToolBarItems.Edit)// Toolbar
item for Editing record.
.Add(GridToolBarItems.Delete)// Toolbar
item for Deleting record.
.Add(GridToolBarItems.Update)// Toolbar
item for save changes.
.Add(GridToolBarItems.Cancel);// Toolbar
item for Cancel request.
}).Render();
}
8. Specify the Primary property which uniquely identifies the grid record.
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("Grid1")
.Caption("Orders")
.AutoFormat(Skins.Sandune)
.ActionMode(ActionMode.JSON)
.Editing( edit=>{
edit.PrimaryKey(key => key.Add(p => p.OrderID)); // Add
the primary key to primary key collections.
})
%>
View [cshtml]
@{ Html.Syncfusion().Grid<Order>("Grid1")
.Caption("Orders")
.AutoFormat(Skins.Sandune)
.ActionMode(ActionMode.JSON)
.Editing( edit=>{
edit.PrimaryKey(key => key.Add(p => p.OrderID)); // Add
the primary key to primary key collections.
}).Render();
}
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("Grid1")
.Caption("Orders")
.AutoFormat(Skins.Sandune)
.ActionMode(ActionMode.JSON)
.Editing( edit=>{
edit.PrimaryKey(key => key.Add(p => p.OrderID)); // Add
primary key to primary key collections.
})
%>
View [cshtml]
@{ Html.Syncfusion().Grid<Order>("Grid1")
.Caption("Orders")
.AutoFormat(Skins.Sandune)
.ActionMode(ActionMode.JSON)
.Editing( edit=>{
edit.PrimaryKey(key => key.Add(p => p.OrderID)); // Add
primary key to primary key collections.
}).Render();
}
Controller
11. In order to work with editing actions, create a Post method for Index actions and bind the
data source to the grid as given in the following code.
Controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new NorthwindDataContext().Orders.ToList();
return data.GridJSONActions<Order>();
}
12. In the controller, create a method to add new records to the grid as displayed below. In this
example, the repository method Add() is being created to insert records to the database.
Refer to the repository action method displayed below.
Controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddOrder(EditableOrder ord)
{
// Repository action method Add is used to insert records into the
datasource.
OrderRepository.Add(ord);
13. In the controller, create a method to save changes as displayed below. In this example, the
repository method Update() is used to update records in the data source.
Controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult OrderSave(EditableOrder ord)
{
// Repository action method Update is used to update the records
into the datasource.
OrderRepository.Update(ord);
14. In the controller, create a method to delete records from the database as displayed below.
In this example, the repository action Delete() will delete the record from the data source.
Controller
[AcceptVerbs(HttpVerbs.Post)]
15. Run the application. The grid will appear as shown below.
Figure 104: Grid with Toolbar Options for Editing, Inserting, and Deleting Records
Essential Grid provides three modes for editing. To change the EditForm mode in editing,
use the EditMode() method.
View [ASPX]
<%=Html.Syncfusion().Grid<EditableOrder>("Grid1")
.ActionMode(ActionMode.JSON)
.Caption("Orders")
.Editing( edit=>{
edit.EditMode(GridEditMode.InlineForm);
})
%>
View [cshtml]
@{ Html.Syncfusion().Grid<EditableOrder>("Grid1")
.ActionMode(ActionMode.JSON)
.Caption("Orders")
.Editing( edit=>{
edit.EditMode(GridEditMode.InlineForm);
}).Render();
}
After configuring the edit mode as InlineForm, the grid will appear in the editing mode as
displayed below.
To use the Templateform editing mode, follow the steps displayed below.
Create the template in partial view, as shown in the following code sample.
<fieldset>
<legend>Fields</legend>
<div class="tablediv">
<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">
<%= Html. LabelFor(model =>
model.OrderID) %>
</div>
<div class="editor-field">
<%= Html. TextBoxFor(model =>
model.OrderID) %>
<%= Html. ValidationMessageFor(model
=> model.OrderID) %>
</div>
</div>
<div class="celldiv" style="height: auto">
<div class="editor-label">
<%= Html. LabelFor(model =>
model.CustomerID) %>
</div>
<div class="editor-field">
<%= Html. TextBoxFor(model =>
model.CustomerID) %>
<%= Html. ValidationMessageFor(model
=> model.CustomerID) %>
</div>
</div>
</div>
<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">
<%= Html. LabelFor(model =>
model.EmployeeID) %>
</div>
<div class="editor-field">
<%= Html. TextBoxFor(model =>
model.EmployeeID) %>
<%= Html. ValidationMessageFor(model
=> model.EmployeeID) %>
</div>
</div>
<div class="celldiv" style="height: auto">
<div class="editor-label">
<%= Html. LabelFor(model =>
model.ShipName) %>
</div>
<div class="editor-field">
<%= Html. TextBoxFor(model =>
model.ShipName) %>
<%= Html. ValidationMessageFor(model
=> model.ShipName) %>
</div>
</div>
</div>
<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">
<%= Html. LabelFor(model =>
model.ShipAddress) %>
</div>
<div class="editor-field">
<%= Html. TextBoxFor(model =>
model.ShipAddress) %>
<%= Html. ValidationMessageFor(model
=> model.ShipAddress) %>
</div>
</div>
View [Razor]
<fieldset>
<legend>Fields</legend>
<div class="tablediv">
<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model => model.OrderID)
</div>
<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model =>
model.OrderID)
@Html.Syncfusion().ValidationMessageFor(model =>
model.OrderID)
</div>
</div>
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model =>
model.CustomerID)
</div>
<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model =>
model.CustomerID)
@Html.Syncfusion().ValidationMessageFor(model =>
model.CustomerID)
</div>
</div>
</div>
<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model =>
model.EmployeeID)
</div>
<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model =>
model.EmployeeID)
@ Html.Syncfusion().ValidationMessageFor(model =>
model.EmployeeID)
</div>
</div>
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model =>
model.ShipName)
</div>
<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model =>
model.ShipName)
@Html.Syncfusion().ValidationMessageFor(model =>
model.ShipName)
</div>
</div>
</div>
<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model =>
model.ShipAddress)
</div>
<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model =>
model.ShipAddress)
@Html.Syncfusion().ValidationMessageFor(model =>
model.ShipAddress)
</div>
</div>
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model => model.ShipCity)
</div>
<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model =>
model.ShipCity)
@ Html.Syncfusion().ValidationMessageFor(model =>
model.ShipCity)
</div>
</div>
</div>
<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model =>
model.ShipRegion)
</div>
<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model =>
model.ShipRegion)
@ Html.Syncfusion().ValidationMessageFor(model =>
model.ShipRegion)
</div>
</div>
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model =>
model.ShipCountry)
</div>
<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model
=>model.ShipCountry)
@Html.Syncfusion().ValidationMessageFor(model =>
model.ShipCountry)
</div>
</div>
</div>
<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model => model.Freight)
</div>
<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model =>
model.Freight)
@Html.Syncfusion().ValidationMessageFor(model =>
model.Freight)
</div>
</div>
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model =>
model.OrderDate)
</div>
<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model =>
model.OrderDate,String.Format("{0:g}", Model.OrderDate))
@Html.Syncfusion().ValidationMessageFor(model =>
model.OrderDate)
</div>
</div>
</div>
</div>
</fieldset>
Note: Don’t specify the form in the template. The <fieldset> tag is required to surround the
template input fields, otherwise the buttons will not be displayed by the dialog.
Configure the GridMode as TemplateFormMode and specify the partial view which contains the
templates.
View [ASPX]
<%=Html.Syncfusion().Grid<EditableOrder>("Grid1")
.ActionMode(ActionMode.JSON)
.Caption("Orders")
.Editing( edit=>{
edit.EditMode(GridEditMode.I
nlineTemplateForm);
edit.FormModeEditorTemplate(
"OrderEditorTemplate");// Specify the partial view page
which contains the
templates.
})
%>
View [cshtml]
@{ Html.Syncfusion().Grid<EditableOrder>("Grid1")
.ActionMode(ActionMode.JSON)
.Caption("Orders")
.Editing( edit=>{
edit.EditMode(GridEditMode.I
nlineTemplateForm);
edit.FormModeEditorTemplate(
"OrderEditorTemplate");// Specify the partial view page
which contains the
templates.
}).Render();
[Site.Master]
<head runat="server">
………
<script src="<%=
Url.Content("~/Scripts/MicrosoftMvcValidation.debug.js") %>"
type="text/javascript"></script>
</head>
[_Layout.cshtml]
<head runat="server">
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server"
/></title>
………
<script
src="@Url.Content("~/Scripts/MicrosoftMvcValidation.debug.js ")"
type="text/javascript"></script>
</head>
Note: Add the following script files when the UnobtrusiveJavaScriptEnabled is true in
web.config file.
[Web.config]
<configuration>
<appSettings>
<add key='UnobtrusiveJavaScriptEnabled' value='true'/>
</appSettings>
[_Layout.cshtml]
<head>
. . . .
. . . .
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")"
type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")"
type="text/javascript"></script>
<script
src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"
type="text/javascript"></script>
</head>
[Site.Master]
<head runat="server">
. . . .
. . . .
<script src="<%=Url.Content("~/Scripts/jquery.unobtrusive-
ajax.min.js")%>" type="text/javascript"></script>
<script src="<%=Url.Content("~/Scripts/jquery.validate.min.js")%>"
type="text/javascript"></script>
<script
src="<%=Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")%
>" type="text/javascript"></script>
</head>
2. Create a model in the application. Refer to How to>Adding a Model to the Application
19. and Editing>EditableOrder Class.
3. Create a strongly typed view (Refer to How to>Strongly Typed View).
4. Add the following code in the Index.aspx file, to create the Grid control in the view.
View [ASPX]
<%=Html.Syncfusion().Grid<EditableOrder>("Orders_Grid","GridModel
", column=> {
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.EmployeeID).HeaderText("Employee ID");
column.Add(p => p.CustomerID).HeaderText("Customer ID");
column.Add(p => p.ShipCountry).HeaderText("Ship Country");
column.Add(p => p.OrderDate).HeaderText("Order
Date").Format("{OrderDate:MM/dd/yyyy}");
column.Add(p => p.Freight).HeaderText("Freight");
})%>
View [cshtml]
@( Html.Syncfusion().Grid<EditableOrder>("Orders_Grid","GridModel",
column=> {
column.Add(p => p.OrderID).HeaderText("Order ID");
}))
5. Create a GridPropertiesModel in the Index method and assign the grid properties in the
model.
Controller
GridPropertiesModel<EditableOrder> model = new
GridPropertiesModel<EditableOrder>()
{
ActionMode = ActionMode.JSON,
Caption = "Orders",
AutoFormat=Skins.Sandune
};
ViewData["GridModel"] = model; // Pass the model from
controller to view using ViewData.
6. Enable editing by using the Editing property in the GridPropertiesModel, and configure
the editing properties such as AllowNew, AllowEdit, and AllowDelete as displayed below.
Controller
// Create an object for grid editing and enable the edit, addnew
and delete actions.
GridEditing edit = new GridEditing() { AllowEdit = true,
AllowDelete = true, AllowNew = true };
edit.EditMode = GridEditMode.Normal;
20.
8. Specify the primary property which uniquely identifies the grid record.
Controller
model.Editing = edit;
22.
10. Essential Grid allows adding new records through grid toolbar items. In this example, the
AddNew, Edit, Delete, Save, and Cancel buttons have been added as toolbar items.
23.
Controller
toolbar.Enable = true;
// Add the Add New, Edit, Delete, Save, and Cancel buttons
to the toolbar.
model.ToolBar = toolbar;
Note: In our earlier versions, the toolbar item collection type is Dictionary<GridToolBarItems
key, string value>. With the inclusion of custom toolbar item support, we can’t add multiple custom
items. The key will be the same (GridToolBarItems.Custom) for all custom items and so we have
modified the toolbar item collection type as List<ToolbarOptions>.
24.
11. In the controller, create a method to add new records to the grid as displayed below. In this
example, the repository method Add() is being created to insert records to the database.
Refer to the repository action method displayed below.
Controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddOrder(EditableOrder ord)
{
// The repository action method Add is used to insert records
into the datasource.
OrderRepository.Add(ord);
return data.GridJSONActions<EditableOrder>();
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult OrderSave(EditableOrder ord)
{
// Repository action method Update is used to update the
records into datasource.
OrderRepository.Update(ord);
13. In the controller, create a method to delete the records from the database as displayed
below. In this example, the repository action Delete() is used to delete the record from the
data source.
26.
Controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult DeleteOrder(int OrderID)
{
// Repository action Delete() deletes the given primary
value record from the datasource.
OrderRepository.Delete(OrderID);
14. In order to work with editing actions, create a Post method for Index actions and bind the
data source to the grid as shown in the following code sample.
27.
Controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new NorthwindDataContext().Orders.ToList();
return data.GridJSONActions<Order>();
}
15. Run the application. The grid will appear as shown in the following screenshots:
Figure 112: Grid with Toolbar Options for Editing, Inserting, and Deleting Records
// Create object to grid editing and enable the edit, addnew, and
delete actions.
GridEditing edit = new GridEditing() { AllowEdit = true,
AllowDelete = true, AllowNew = true };
// Set the Edit mode.
edit.EditMode = GridEditMode.InlineForm;
If the edit mode is configured as InlineForm, the grid will appear as displayed below.
</div>
<div class="celldiv" style="height: auto">
<div class="editor-label">
<%= Html. LabelFor(model =>
model.CustomerID) %>
</div>
<div class="editor-field">
<%= Html. TextBoxFor(model =>
model.CustomerID) %>
<%= Html. ValidationMessageFor(model
=> model.CustomerID) %>
</div>
</div>
</div>
<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">
<%= Html. LabelFor(model =>
model.EmployeeID) %>
</div>
<div class="editor-field">
<%= Html. TextBoxFor(model =>
model.EmployeeID) %>
<%= Html. ValidationMessageFor(model
=> model.EmployeeID) %>
</div>
</div>
<div class="celldiv" style="height: auto">
<div class="editor-label">
<%= Html. LabelFor(model =>
model.ShipName) %>
</div>
<div class="editor-field">
<%= Html. TextBoxFor(model =>
model.ShipName) %>
<%= Html. ValidationMessageFor(model
=> model.ShipName) %>
</div>
</div>
</div>
<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">
<%= Html. LabelFor(model =>
model.ShipAddress) %>
</div>
<div class="editor-field">
<%= Html. TextBoxFor(model =>
model.ShipAddress) %>
<%= Html. ValidationMessageFor(model
=> model.ShipAddress) %>
</div>
</div>
<div class="celldiv" style="height: auto">
<div class="editor-label">
<%= Html. LabelFor(model =>
model.ShipCity) %>
</div>
<div class="editor-field">
<%= Html. TextBoxFor(model =>
model.ShipCity) %>
<%= Html. ValidationMessageFor(model
=> model.ShipCity) %>
</div>
</div>
</div>
<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">
<%= Html. LabelFor(model =>
model.ShipRegion) %>
</div>
<div class="editor-field">
<%= Html. TextBoxFor(model =>
model.ShipRegion) %>
<%= Html. ValidationMessageFor(model
=> model.ShipRegion) %>
</div>
</div>
<div class="celldiv" style="height: auto">
<div class="editor-label">
<%= Html. LabelFor(model =>
model.ShipCountry) %>
</div>
<div class="editor-field">
<%= Html. TextBoxFor(model =>
model.ShipCountry) %>
<%= Html. ValidationMessageFor(model
=> model.ShipCountry) %>
</div>
</div>
</div>
<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">
<%= Html. LabelFor(model =>
model.Freight) %>
</div>
<div class="editor-field">
<%= Html. TextBoxFor(model =>
model.Freight) %>
<%= Html. ValidationMessageFor(model
=> model.Freight) %>
</div>
</div>
<div class="celldiv" style="height: auto">
<div class="editor-label">
<%= Html. LabelFor(model =>
model.OrderDate) %>
</div>
<div class="editor-field">
<%= Html. TextBoxFor(model =>
model.OrderDate, String.Format("{0:g}",
Model.OrderDate)) %>
<%= Html. ValidationMessageFor(model
=> model.OrderDate) %>
</div>
</div>
</div>
</div>
</fieldset>
View [Razor]
<fieldset>
<legend>Fields</legend>
<div class="tablediv">
<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model => model.OrderID)
</div>
<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model =>
model.OrderID)
@Html.Syncfusion().ValidationMessageFor(model =>
model.OrderID)
</div>
</div>
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model =>
model.CustomerID)
</div>
<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model =>
model.CustomerID)
@Html.Syncfusion().ValidationMessageFor(model =>
model.CustomerID)
</div>
</div>
</div>
<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model =>
model.EmployeeID)
</div>
<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model =>
model.EmployeeID)
@ Html.Syncfusion().ValidationMessageFor(model =>
model.EmployeeID)
</div>
</div>
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model =>
model.ShipName)
</div>
<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model =>
model.ShipName)
@Html.Syncfusion().ValidationMessageFor(model =>
model.ShipName)
</div>
</div>
</div>
<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model =>
model.ShipAddress)
</div>
<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model =>
model.ShipAddress)
@Html.Syncfusion().ValidationMessageFor(model =>
model.ShipAddress)
</div>
</div>
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model => model.ShipCity)
</div>
<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model =>
model.ShipCity)
@ Html.Syncfusion().ValidationMessageFor(model =>
model.ShipCity)
</div>
</div>
</div>
<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model =>
model.ShipRegion)
</div>
<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model =>
model.ShipRegion)
@ Html.Syncfusion().ValidationMessageFor(model =>
model.ShipRegion)
</div>
</div>
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model =>
model.ShipCountry)
</div>
<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model
=>model.ShipCountry)
@Html.Syncfusion().ValidationMessageFor(model =>
model.ShipCountry)
</div>
</div>
</div>
<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model => model.Freight)
</div>
<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model =>
model.Freight)
@Html.Syncfusion().ValidationMessageFor(model =>
model.Freight)
</div>
</div>
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model =>
model.OrderDate)
</div>
<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model =>
model.OrderDate,String.Format("{0:g}", Model.OrderDate))
@Html.Syncfusion().ValidationMessageFor(model =>
model.OrderDate)
</div>
</div>
</div>
</div>
</fieldset>
Note: Don’t specify the form in the template. And the <fieldset> tag is required to surround the
template input fields else the buttons will not be displayed by the dialog.
2. Configure the GridMode as TemplateFormMode and specify the partial view which
contains the templates.
Controller
// Create an object to grid editing and enable the
edit, addnew, and delete actions.
GridEditing edit = new GridEditing() {
AllowEdit = true, AllowDelete = true, AllowNew = true };
Events
Event Description Arguments Type Reference links
The client-side events are used in ASPX as shown in the following code table in server mode
through GridBuilder.
View[ASPX]
<%=Html.Syncfusion().Grid<Order>("GridSrc")
.Datasource(Model)
.Caption("Order Grid")
.AutoFormat(Skins.Almond)
.Editing( edit=>{
For Razor, use the code shown below in the following table in server mode through GridBuilder.
View[cshtml]
@{
Html.Syncfusion().Grid<Order>("GridSrc")
.Datasource(Model)
.Caption("Order Grid")
.AutoFormat(Skins.Almond)
.Editing( edit=>{
Sample Link
To view the samples, follow the steps below:
1. Open the Grid sample browser from the dashboard (Refer to the Samples and Location
chapter).
2. Navigate to Grid.MVC > Editing > JSON Mode
4.7.3.1 Properties
Property Description Type of Value it Reference
</head>
[_Layout.cshtml]
<head runat="server">
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server"
/></title>
………
<script
src="@Url.Content("~/Scripts/MicrosoftMvcValidation.debug.js ")"
type="text/javascript"></script>
</head>
Note: Add the following script files when the UnobtrusiveJavaScriptEnabled is true in
web.config file.
[Web.config]
<configuration>
<appSettings>
<add key='UnobtrusiveJavaScriptEnabled' value='true'/>
</appSettings>
[_Layout.cshtml]
<head>
. . . .
. . . .
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")"
type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")"
type="text/javascript"></script>
<script
src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"
type="text/javascript"></script>
</head>
[Site.Master]
<head runat="server">
. . . .
. . . .
<script src="<%=Url.Content("~/Scripts/jquery.unobtrusive-
ajax.min.js")%>" type="text/javascript"></script>
<script src="<%=Url.Content("~/Scripts/jquery.validate.min.js")%>"
type="text/javascript"></script>
<script
src="<%=Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")%
>" type="text/javascript"></script>
</head>
2. Create a model in the application. (Refer to How to > Adding a Model to the Application and
Editing > EditableOrder Class.)
3. Create a strongly typed view. (Refer to How to > Strongly Typed View.)
4. In the view, use the Model property in Datasource() to bind the data source.
5. Enable editing by using the Editing method and configure the editing properties:
AllowNew, AllowEdit, and AllowDelete.
6. Essential Grid allows adding new records through grid toolbar items. (Refer to Concepts
and Features > Editing).
7. Specify the primary property that uniquely identifies the grid record. Specify the GridEditing
mode using the EditMode() method. (Refer to Concepts and Features > Editing).
8. Specify the new row position using the AddNewRowPosition property.
View [ASPX]
<%=Html.Syncfusion().Grid< EditableOrder>("Grid1")
.Datasource(Model)
.Caption("Orders")
.AutoFormat(Skins.Sandune)
.Column( columns => {
columns.Add(p => p.OrderID).HeaderText("Order ID");
columns.Add(p => p.ShipCountry).HeaderText("Ship
Country").CellEditType(CellEditType.DropdownEdit);
columns.Add(p => p.ShipCity).HeaderText("Ship City");
columns.Add(p => p.CustomerID).HeaderText("Customer ID");
columns.Add(p => p.ShipAddress).HeaderText("Ship Address");
columns.Add(p => p.OrderDate).HeaderText("Order Date");
columns.Add(p => p.Freight);
})
.Editing(edit =>
{
edit.AllowEdit(true)
.AddNewRowPosition(RowPosition.Bottom)
.AllowNew(true)
.AllowDelete(true)
.EditMode(GridEditMode.Normal)
.PrimaryKey(key => key.Add(p => p.OrderID));
})
.EnablePaging()
.EnableSorting()
.EnableFiltering()
%>
View [cshtml]
@{ Html.Syncfusion().Grid< EditableOrder>("Grid1")
.Datasource(Model)
.Caption("Orders")
.AutoFormat(Skins.Sandune)
.Column( columns => {
columns.Add(p => p.OrderID).HeaderText("Order ID");
columns.Add(p => p.ShipCountry).HeaderText("Ship
Country").CellEditType(CellEditType.DropdownEdit);
columns.Add(p => p.ShipCity).HeaderText("Ship City");
columns.Add(p => p.CustomerID).HeaderText("Customer ID");
columns.Add(p => p.ShipAddress).HeaderText("Ship Address");
columns.Add(p => p.OrderDate).HeaderText("Order Date");
columns.Add(p => p.Freight);
})
.Editing(edit =>
{
edit.AllowEdit(true)
.AddNewRowPosition(RowPosition.Bottom)
.AllowNew(true)
.AllowDelete(true)
.EditMode(GridEditMode.Normal)
.PrimaryKey(key => key.Add(p => p.OrderID));
})
.EnablePaging()
.EnableSorting()
.EnableFiltering()
.Render();
}
9. In the controller, create a method to add new records to the grid, as displayed below. In this
example, the repository method Add() is being created to insert records in the database.
Refer to the repository action method shown below.
Controller
/// <summary>
/// Used to insert the record in the database and refresh the grid.
/// </summary>
/// <param name="ord">Editable order.</param>
/// <returns>HtmlActionResult returns the data displayed in the
grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddOrder(EditableOrder ord)
{
// Repository action method Add() is used to insert records in the data
source.
OrderRepository.Add(ord);
// After adding the record to the database, refresh the grid.
var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}
10. In the controller, create a method to save changes. In this example, the repository method
Update() is used to update records to the data source.
Controller
/// Used to insert the record in the database and refresh the grid.
/// </summary>
/// <param name="ord">Editable order.</param>
/// <returns>HtmlActionResult returns the data displayed in the
grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult OrderSave(EditableOrder ord)
{
// The repository action method Update is used to update the records to
the data source.
OrderRepository.Update(ord);
// After saving the records to the data source, refresh the grid.
var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}
11. In the controller, create a method to delete the records from the database. In this example,
the repository action Delete() will delete the record from the data source.
Controller
/// <summary>
/// Used to delete records from the data source and refresh the grid.
/// </summary>
/// <param name="OrderID">Primary key values.</param>
/// <returns>HtmlActionResult returns the data displayed in the
grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult DeleteOrder(int OrderID)
{
// Repository action Delete() deletes the given primary-value record
from the data source.
OrderRepository.Delete(OrderID);
// After deleting, refresh the grid.
var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}
12. Run the application. The grid will appear as shown below.
Figure 121: Grid with Toolbar Options for Editing, Inserting, and Deleting
The following image shows the new edit-row position when the Add New Record button, located
in the toolbar, is clicked.
</head>
[_Layout.cshtml]
<head runat="server">
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server"
/></title>
………
<script
src="@Url.Content("~/Scripts/MicrosoftMvcValidation.debug.js ")"
type="text/javascript"></script>
</head>
Note: Add the following script files when the UnobtrusiveJavaScriptEnabled is true in
web.config file.
[Web.config]
<configuration>
<appSettings>
<add key='UnobtrusiveJavaScriptEnabled' value='true'/>
</appSettings>
[_Layout.cshtml]
<head>
. . . .
. . . .
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")"
type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")"
type="text/javascript"></script>
<script
src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"
type="text/javascript"></script>
</head>
[Site.Master]
<head runat="server">
. . . .
. . . .
<script src="<%=Url.Content("~/Scripts/jquery.unobtrusive-
ajax.min.js")%>" type="text/javascript"></script>
<script src="<%=Url.Content("~/Scripts/jquery.validate.min.js")%>"
type="text/javascript"></script>
<script
src="<%=Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")%
>" type="text/javascript"></script>
</head>
2. Create a model in the application. (Refer to How to > Adding a Model to the
Application and Editing > EditableOrder Class.)
3. Create a strongly typed view (Refer to How to>Strongly Typed View).
4. Add the following code in the Index.aspx file to create the Grid control in the
view.
View [ASPX]
<%=Html.Syncfusion().Grid<EditableOrder>("Orders_Grid","GridModel",
columns => {
columns.Add(p => p.OrderID).HeaderText("Order ID");
columns.Add(p => p.ShipCountry).HeaderText("Ship
Country").CellEditType(CellEditType.DropdownEdit);
columns.Add(p => p.ShipCity).HeaderText("Ship City");
columns.Add(p => p.CustomerID).HeaderText("Customer ID");
columns.Add(p => p.ShipAddress).HeaderText("Ship Address");
columns.Add(p => p.OrderDate).HeaderText("Order Date");
columns.Add(p => p.Freight);
})
%>
View [cshtml]
@( Html.Syncfusion().Grid<EditableOrder>("Orders_Grid","GridModel",
columns => {
columns.Add(p => p.OrderID).HeaderText("Order ID");
columns.Add(p => p.ShipCountry).HeaderText("Ship
Country").CellEditType(CellEditType.DropdownEdit);
columns.Add(p => p.ShipCity).HeaderText("Ship City");
columns.Add(p => p.CustomerID).HeaderText("Customer ID");
columns.Add(p => p.ShipAddress).HeaderText("Ship Address");
columns.Add(p => p.OrderDate).HeaderText("Order Date");
columns.Add(p => p.Freight);
})
)
5. Create GridPropertiesModel in the Index action and assign the grid properties
in the model.
Controller
8. Specify the Primary property, which uniquely identifies the grid record.
9. Add the edit setting to the model. Essential Grid allows new records to be edited
by using toolbar items. (Refer to Concepts and Features > Editing.)
10. Specify the position of the new editing-row by using the AddNewRowPosition
property.
Controller
Controller
12. Essential Grid allows new records to be added through toolbar items. In the
following example, AddNew, Edit, Delete, Save, and Cancel buttons have been
added as toolbar items.
Controller
13. In the controller, create a method to add new records to the grid. In this example,
the repository method Add() has been created to insert records in the database.
Note the repository action method shown in the following code.
Controller
/// <summary>
/// Used to insert the record in the database and refresh the grid.
/// </summary>
/// <param name="ord">Editable order.</param>
/// <returns>HtmlActionResult returns the data displayed in the
grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddOrder(EditableOrder ord)
{
// The repository action method Add() is used to insert records in the
data source.
OrderRepository.Add(ord);
// After adding the record to the database, refresh the grid.
var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}
14. In the controller, create a method to save changes. In this example, the
repository method Update() is used to update records to the data source:
Controller
/// Used to insert the record in the database and refresh the grid.
/// </summary>
/// <param name="ord">Editable order.</param>
/// <returns>HtmlActionResult returns the data displayed in the
grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult OrderSave(EditableOrder ord)
{
// The repository action method Update is used to update the records to
the data source.
OrderRepository.Update(ord);
//After saving the records to the data source, refresh the grid.
var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}
15. In the controller, create a method to delete the records from the database. In this
example, the repository action Delete() will delete the record from the data
source.
Controller
/// <summary>
/// Used to delete records from the data source and refresh the grid.
/// </summary>
/// <param name="OrderID">Primary key values.</param>
/// <returns>HtmlActionResult returns the data displayed in the
grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
16. Run the application. The grid will appear as shown in the following image.
Figure 123: Grid with Toolbar Options for Editing, Inserting, and Deleting
The following image shows the new edit-row position when the Add New Record button, located
in the toolbar, is clicked.
Sample Link
To view the samples, follow the steps below:
1. Open the Grid sample browser from the dashboard (Refer to the Samples and Location
chapter).
2. Navigate to Grid.MVC > Editing > Server Mode/JSON Mode
4.7.4 CellEditType
Essential Grid for ASP.NET MVC supports CellEditType by using delegated controls for specific
data types such as the CheckBox control for Boolean data types; NumericTextBox control for
integers, double, and decimal types; DatePicker control for date-time data; and DropDownList
control for lists of data. The edit type of every column can be customized using the CellEditType
property.
GridBuilder
GridPropertiesModel
[Site.Master]
<head runat="server">
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server"
/></title>
………
<script src="<%=
Url.Content("~/Scripts/MicrosoftMvcValidation.debug.js") %>"
type="text/javascript"></script>
</head>
[_Layout.cshtml]
<head runat="server">
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server"
/></title>
………
<script
src="@Url.Content("~/Scripts/MicrosoftMvcValidation.debug.js ")"
type="text/javascript"></script>
</head>
Note: Add the following script files when the UnobtrusiveJavaScriptEnabled is true in
web.config file.
[Web.config]
<configuration>
<appSettings>
<add key='UnobtrusiveJavaScriptEnabled' value='true'/>
</appSettings>
[_Layout.cshtml]
<head>
. . . .
. . . .
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")"
type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")"
type="text/javascript"></script>
<script
src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"
type="text/javascript"></script>
</head>
[Site.Master]
<head runat="server">
. . . .
. . . .
<script src="<%=Url.Content("~/Scripts/jquery.unobtrusive-
ajax.min.js")%>" type="text/javascript"></script>
<script src="<%=Url.Content("~/Scripts/jquery.validate.min.js")%>"
type="text/javascript"></script>
<script
src="<%=Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")%
>" type="text/javascript"></script>
</head>
2. Create a model in the application. Refer to How to > Adding a Model to the Application and
Editing > EditableOrder Class.
3. Create a strongly typed view. Refer to How to > Strongly Typed View.
4. In the view, use the Model property in the Datasource() to bind the data source.
5. Enable editing by using the Editing method and configure the editing properties such as
AllowNew, AllowEdit, and AllowDelete.
6. Essential Grid allows adding new records through grid toolbar items. Refer to Concepts and
Features > Editing.
7. Specify the primary property which uniquely identifies the grid record. Specify the
GridEditing mode using the EditMode() method. Refer to Concepts and Features >
Editing.
View [ASPX]
<%=Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model)
.Caption("Orders")
.Column(column =>
{
column.Add(p =>
p.OrderID).HeaderText("Order ID");
column.Add(p =>
p.EmployeeID).HeaderText("Employee
ID").NumericEditParams(n=>n.MinValue(0).MaxValue(9));
column.Add(p =>
p.CustomerID).HeaderText("Customer
ID").CellEditType(CellEditType.MaskEdit).MaskEditParams(m =>
m.Mask("aaaaa").WaterMarkText("aaaaa"));
column.Add(p =>
p.Verified).HeaderText("Verified");
column.Add(p =>
p.ShipRegion).HeaderText("Ship
Region").CellEditType(CellEditType.DropdownEdit);
column.Add(p =>
p.Freight).HeaderText("Freight").CellEditType(CellEditType.PercentEdit)
.PercentEditParams(p=>p.MaxValue(100).MinValue(0));
})
.EnablePaging()
.EnableSorting()
.EnableGrouping()
%>
View [cshtml]
@{ Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model)
.Caption("Orders")
.Column(column =>
{
column.Add(p =>
p.OrderID).HeaderText("Order ID");
column.Add(p =>
p.EmployeeID).HeaderText("Employee
ID").NumericEditParams(n=>n.MinValue(0).MaxValue(9));
column.Add(p =>
p.CustomerID).HeaderText("Customer
ID").CellEditType(CellEditType.MaskEdit).MaskEditParams(m =>
m.Mask("aaaaa").WaterMarkText("aaaaa"));
column.Add(p =>
p.Verified).HeaderText("Verified");
column.Add(p =>
p.ShipRegion).HeaderText("Ship
Region").CellEditType(CellEditType.DropdownEdit);
column.Add(p =>
p.Freight).HeaderText("Freight").CellEditType(CellEditType.PercentEdit)
.PercentEditParams(p=>p.MaxValue(100).MinValue(0));
})
.EnablePaging()
.EnableSorting()
.EnableGrouping()
.Render();
}
8. In the controller, create a method to add new records to the grid as shown in the following
code. In this example, the repository method Add() is being created to insert records in the
database. Refer to the repository action method given below.
Controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddOrder(EditableOrder ord)
{
//Repository action method Add used to insert records into the
data source.
OrderRepository.Add(ord);
9. In the controller, create a method to save changes as shown in the following code sample.
In this example, the repository method Update() is used to update records to the data
source.
Controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult OrderSave(EditableOrder ord)
{
//Repository action method Update is used to update the
records into the datasource.
OrderRepository.Update(ord);
10. Run the application. The grid will appear as shown below:
Figure 126: Grid with Toolbar Options for Editing, Inserting, and Deleting
The following screenshot shows default editor-type controls such as NumericTextBox for integer
types (namely “Employee ID”), NumericTextbox for decimal types (namely “Freight”), and
CheckBox for Boolean types (namely “Verified” column).
The steps to work with the CellEditType feature using GridPropertiesModel are as follows:
[Site.Master]
<head runat="server">
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server"
/></title>
………
<script src="<%=
Url.Content("~/Scripts/MicrosoftMvcValidation.debug.js") %>"
type="text/javascript"></script>
</head>
[_Layout.cshtml]
<head runat="server">
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server"
/></title>
………
<script
src="@Url.Content("~/Scripts/MicrosoftMvcValidation.debug.js ")"
type="text/javascript"></script>
</head>
28.
Note: Add the following script files when the UnobtrusiveJavaScriptEnabled is true in
web.config file.
[Web.config]
<configuration>
<appSettings>
<add key='UnobtrusiveJavaScriptEnabled' value='true'/>
</appSettings>
[_Layout.cshtml]
<head>
. . . .
. . . .
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")"
type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")"
type="text/javascript"></script>
<script
src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"
type="text/javascript"></script>
</head>
[Site.Master]
<head runat="server">
. . . .
. . . .
<script src="<%=Url.Content("~/Scripts/jquery.unobtrusive-
ajax.min.js")%>" type="text/javascript"></script>
<script src="<%=Url.Content("~/Scripts/jquery.validate.min.js")%>"
type="text/javascript"></script>
<script
src="<%=Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")%
>" type="text/javascript"></script>
</head>
2. Create a model in the application. Refer to How to>Adding a Model to the Application and
Editing>EditableOrder Class.
3. Create a strongly typed view (Refer to How to>Strongly Typed View).
4. Add the following code in the Index.aspx file to create the Grid control in the view.
View [ASPX]
<%=Html.Syncfusion().Grid<Editing.Models.EditableOrder>("Orders_G
rid",
(GridPropertiesModel<Editing.Models.EditableOrder>)ViewData["GridModel"
]).ToString())%>
View [cshtml]
@( Html.Syncfusion().Grid<Editing.Models.EditableOrder>("Orders_Grid",
(GridPropertiesModel<Editing.Models.EditableOrder>)ViewData["GridModel"
]).ToString()))
5. Create a GridPropertiesModel in the Index action and assign the grid properties in the
model.
Controller
},
new GridColumn<EditableOrder>
{
HeaderText = "Verified",
MappingName = "Verified",
ColumnType=typeof(bool)
},
new GridColumn<EditableOrder>
{
HeaderText = "Ship Region",
MappingName = " ShipRegion ",
ColumnType=typeof(string),
CellEditType =
Syncfusion.Mvc.Grid.CellEditType.DropdownEdit
},
new GridColumn<EditableOrder>
{
HeaderText = "Freight",
MappingName = "Freight",
ColumnType=typeof(decimal),
CellEditType=
Syncfusion.Mvc.Grid.CellEditType.PercentEdit,
PercentEditParams = new PercentTextBoxModel(){
MinValue = 0, MaxValue = 100}
},
};
ViewData["GridModel"] = model;
return View();
6. Enable editing by using the Editing property in the GridPropertiesModel and configure the
editing properties such as AllowNew, AllowEdit, and AllowDelete.
7. Specify the grid editing mode using the EditMode property.
8. Specify the Primary property which uniquely identifies the grid record.
9. Add the edit setting to the model.
10. Essential Grid allows adding new records using grid toolbar items. Refer to Concepts and
Features>Editing.
11. In the controller, create a method to add new records to the grid as given below. In this
example, the repository method Add() is being created to insert records in the database.
Refer to the repository action method given in the following code.
Controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddOrder(EditableOrder ord)
{
//Repository action method Add used for perform inserting
records into datasource
OrderRepository.Add(ord);
12. In the controller, create a method to save changes, as shown in the following code. In this
example, the repository method Update() is used to update records in the data source.
Controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult OrderSave(EditableOrder ord)
{
//Repository action method Update used for perform update
the records into datasource
OrderRepository.Update(ord);
13. Run the application. The grid will appear as shown in the following screenshot.
Figure 129: Grid with Toolbar Options for Editing, Inserting, and Deleting Records
The following screenshot shows the default editor-type controls such as NumericTextBox for
integer types (namely “Employee ID”), NumericTextbox for decimal types (namely “Freight”), and
CheckBox for Boolean types (namely the “Verified” column).
The following table illustrates the properties under GridColumn, which is relevant to
CellEditType functionality.
CellEditType. MaskEdit,
CellEditType. NumericEdit
The following table illustrates the CellEditType option usages and controls.
Sample Link
To view the samples:
29. Open the ASP.NET MVC Sample Browser from the dashboard. (Refer to the Samples and
Location chapter)
30. Navigate to Grid>Editing>Cell Edit Type demo.
Feature Summary
The Excel-like edit feature allows you to edit data similarly to how one can edit it using Microsoft
Excel. This is more suitable for extremely large edits, since it reduces the time required to save all
the edited data to the server side.
This feature in Essential Grid for MVC has two modes:
Manual Excel—This allows you to edit large amounts of data and then save it on to the
server side whenever you need to.
Auto Excel—This option automatically updates the server with edited information, at fixed
time intervals.
Both of these modes allow you to keep editing as much data as required for as long as required.
Edited data is marked on the grid so that you know which fields or cells have been edited.
These markers are not shown after the updated data is rendered.
The following figure gives you a basic idea of the appearance of a grid in the Excel-like edit
mode:
Properties
Type of
Property Description Value it accepts Dependencies
property
Depends on
AllowEditing—
Depends on
EditMode—
Used to specify the
time interval at which int
TimeSpan Any integer value
data is saved to the Only if the EditMode
server. is set to AutoExcel
will this property will
be activated.
Events
colObj—columnObject
contains information about
column objects such as
Triggered before the edit form of the cell name, type, header text, etc.
OnCellEdit
being edited is rendered.
colObj—columnObject
contains information about
column objects, such as
Triggered before the value of the
name, type, header text, etc.
OnCellSave particular cells being edited are saved in
the client side.
value—Contains the updated
value of the cell.
updatedRecords—contains
Triggered before the updated records are the list of updated records.
OnBulkSave
saved in the server side.
deletedRecords—contains
the list of deleted records.
insertedRecords—contains
the list of inserted records.
colObj—columnObject
contains information about
column objects such as
Triggered before the updated records are name, type, header text, etc.
OnCancel
canceled for saving in the server side.
<head runat="server">
………
<script src="<%=
Url.Content("~/Scripts/MicrosoftMvcValidation.debug.js") %>"
type="text/javascript"></script>
</head>
31.
[_Layout.cshtml]
<head runat="server">
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server"
/></title>
………
<script
src="@Url.Content("~/Scripts/MicrosoftMvcValidation.debug.js ")"
type="text/javascript"></script>
</head>
Note: Add the following script files when the UnobtrusiveJavaScriptEnabled is true in
web.config file.
[Web.config]
<configuration>
<appSettings>
<add key='UnobtrusiveJavaScriptEnabled' value='true'/>
</appSettings>
[_Layout.cshtml]
<head>
. . . .
. . . .
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")"
type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")"
type="text/javascript"></script>
<script
src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"
type="text/javascript"></script>
</head>
[Site.Master]
<head runat="server">
. . . .
. . . .
<script src="<%=Url.Content("~/Scripts/jquery.unobtrusive-
ajax.min.js")%>" type="text/javascript"></script>
<script src="<%=Url.Content("~/Scripts/jquery.validate.min.js")%>"
type="text/javascript"></script>
<script
src="<%=Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")%
>" type="text/javascript"></script>
</head>
View[ASPX]
<%=Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model).ActionMode(ActionMode.JSON)
.Caption("Orders")
.Column(column =>
{
column.Add(p =>
p.OrderID).HeaderText("Order ID");
column.Add(p =>
p.CustomerID).HeaderText("Customer ID");
column.Add(p =>
p.ShipCountry).HeaderText("Ship
Country").CellEditType(CellEditType.DropdownEdit);
column.Add(p =>
p.OrderDate).HeaderText("Order Date").Format("{0:MM/dd/yyyy}");
column.Add(p =>
p.Freight).HeaderText("Freight").Format("{0:C}");
column.Add(p =>
p.Delivered).HeaderText("Delivered");
})
%>
View[cshtml]
@{ Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model).ActionMode(ActionMode.JSON)
.Caption("Orders")
.Column(column =>
{
column.Add(p =>
p.OrderID).HeaderText("Order ID");
column.Add(p =>
p.CustomerID).HeaderText("Customer ID");
column.Add(p =>
p.ShipCountry).HeaderText("Ship
Country").CellEditType(CellEditType.DropdownEdit);
column.Add(p =>
p.OrderDate).HeaderText("Order Date").Format("{0:MM/dd/yyyy}");
column.Add(p =>
p.Freight).HeaderText("Freight").Format("{0:C}");
column.Add(p =>
p.Delivered).HeaderText("Delivered");
})
.Render();
5. Enable the Excel-like editing mode by setting the edit mode to AutoExcel (or ManualExcel)
and configuring the editing property AllowEdit which specifies the action method.This will
perform the save operation, as displayed below.Set the TimeSpan property which is used in
saving the records automatically after the specified time interval in the AutoExcel edit mode.
View[ASPX]
<%=Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model).ActionMode(ActionMode.JSON)
.Editing( edit=>{
edit.AllowEdit(true, "Home/BulkSave");// Specify the action method
which will perform the update action.
edit.EditMode(GridEditMode.AutoExcel);// Specify the grid edit mode.
edit.TimeSpan(3000);
edit.PrimaryKey(key => key.Add(p => p.OrderID)); // Add primary
key to primary key collections.
})
%>
View[cshtml]
@{ Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model).ActionMode(ActionMode.JSON)
.Editing( edit=>{
edit.AllowEdit(true, "Home/BulkSave");// Specify the controller and
Note: If you want to specify the URL in the AllowEdit property itself means, specify the controller
and the corresponding action name as a URL. If you using the Mappers property then there is no
need to specify the controller name.
6. Essential Grid allows adding new records through grid toolbar items. In this
example, AddNew, Edit, Delete, Save, and Cancel buttons have been added as toolbar
items as displayed below:
View[ASPX]
<%=Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model).ActionMode(ActionMode.JSON)
.ToolBar(tools =>
{
tools.Add(GridToolBarItems.AddNew)// Toolbar item for inserting
records.
.Add(GridToolBarItems.Edit) )// Toolbar item for editing
records.
.Add(GridToolBarItems.Delete)// Toolbar item for deleting
records.
.Add(GridToolBarItems.Update)// Toolbar item for saving
records.
.Add(GridToolBarItems.Cancel);// Toolbar item for canceling
request.
})
%>
View[cshtml]
@{ Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model).ActionMode(ActionMode.JSON)
.ToolBar(tools =>
{
tools.Add(GridToolBarItems.AddNew)// Toolbar item for inserting
records.
.Add(GridToolBarItems.Edit) )// Toolbar item for editing
records.
.Add(GridToolBarItems.Delete)// Toolbar item for deleting
records.
7. In the controller, create a method to save changes as displayed below. In this example, the
repository method BulkSave() is used to update records to the data source. In the function
below, we can get the list of updated records through the parameter updatedRcds using
the bind prefix updatedRecords. In the same way we can get the list of added and deleted
records using the bind prefix addedRecords and deletedRecords respectively.
Controller
///<summary>
/// Used to update the records in the database and refresh the grid.
/// </summary>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult BulkSave([Bind(Prefix =
"updatedRecords")]IEnumerable<EditableOrder> updatedRcds, [Bind(Prefix
= "addedRecords")]IEnumerable<EditableOrder> addedRcds, [Bind(Prefix =
"deletedRecords")]IEnumerable<EditableOrder> deletedRcds)
{
if (updatedRcds != null)
OrderRepository.Update(updatedRcds);
if (addedRcds != null)
OrderRepository.Add(addedRcds);
if (deletedRcds != null)
OrderRepository.Delete(deletedRcds);
// After the records are saved to the data source, refresh the
grid.
var data = OrderRepository.GetAllRecords();
return data.GridJSONActions<EditableOrder>();
}
32. The updated cells will be indicated bythe red color mark. The changes will be saved
automatically after the specified time interval.
<head runat="server">
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server"
/></title>
………
<script src="<%=
Url.Content("~/Scripts/MicrosoftMvcValidation.debug.js") %>"
type="text/javascript"></script>
</head>
[_Layout.cshtml]
<head runat="server">
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server"
/></title>
………
<script
src="@Url.Content("~/Scripts/MicrosoftMvcValidation.debug.js ")"
type="text/javascript"></script>
</head>
Note: Add the following script files when the UnobtrusiveJavaScriptEnabled is true in
web.config file.
[Web.config]
<configuration>
<appSettings>
<add key='UnobtrusiveJavaScriptEnabled' value='true'/>
</appSettings>
[_Layout.cshtml]
<head>
. . . .
. . . .
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")"
type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")"
type="text/javascript"></script>
<script
src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"
type="text/javascript"></script>
</head>
[Site.Master]
<head runat="server">
. . . .
. . . .
<script src="<%=Url.Content("~/Scripts/jquery.unobtrusive-
ajax.min.js")%>" type="text/javascript"></script>
<script src="<%=Url.Content("~/Scripts/jquery.validate.min.js")%>"
type="text/javascript"></script>
<script
src="<%=Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")%
>" type="text/javascript"></script>
</head>
View[ASPX]
})%>
View[cshtml]
Controller
ViewData["GridModel"] = model;
33.
6. Enable the Excel-like editing mode by setting the edit mode to AutoExcel (or
ManualExcel). Configure the editing property AllowEdit which specifies the
action method that will perform the save operation as displayed below. Set the
TimeSpan property which is used in saving the records automatically after the
specified time interval in AutoExcel edit mode.
Controller
7. Specify the primary property which uniquely identifies the grid record.
Controller
9. Grid allows adding new records through grid toolbar items. In this example,
AddNew, Edit, Delete, Save, and Cancel buttons have been added in the toolbar
items. Therefore, configure the toolbar, as displayed below:
36.
Controller
// Configure the toolbar.
ToolbarSettings toolbar = new ToolbarSettings();
toolbar.Enable = true;
// Add the Add New, Edit, Delete, Save, and Cancel buttons to the
toolbar.
model.ToolBar = toolbar;
10. In the controller, create a method to save changes, as displayed below. In this
example, the repository method BulkSave() is used to update records to the data
source. In the below function, we can get the list of updated records through
parameter “updatedRcds” using the bind prefix "updatedRecords". In the same
way we can get the list of added and deleted records using the bind prefix
“addedRecords” and “deletedRecords” respectively.
Controller
///<summary>
/// Used to update the records in the database and refresh the grid.
/// </summary>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult BulkSave([Bind(Prefix =
"updatedRecords")]IEnumerable<EditableOrder> updatedRcds, [Bind(Prefix
= "addedRecords")]IEnumerable<EditableOrder> addedRcds, [Bind(Prefix =
"deletedRecords")]IEnumerable<EditableOrder> deletedRcds)
{
if (updatedRcds != null)
OrderRepository.Update(updatedRcds);
if (addedRcds != null)
OrderRepository.Add(addedRcds);
if (deletedRcds != null)
OrderRepository.Delete(deletedRcds);
// After saving the records to the data source, refresh the grid.
var data = OrderRepository.GetAllRecords();
return data.GridJSONActions<EditableOrder>();
}
11. Run the application and edit the data as displayed below:
37.
38. The updated cells will be indicated by using the red color mark. The changes will be saved
automatically after the specified time interval.
39.
Sample Link
To view the samples, follow the steps below:
1. Open the Grid sample browser from the dashboard (Refer to the Samples and Location
chapter).
2. Navigate to Grid.MVC > Editing > Excel Like Edit
40.
The Dialog Edit feature allows you to edit data, using a dialog box, which contains fields
associated with the data record being edited.
You can edit data in two ways using this feature:
Using the Dialog mode—This allows you to edit data of a particular record using the
Dialog box. You can only edit the data stored in the fields that you have rendered to be
visible.
Using the Dialog Template mode—This allows you to create a template for the data
that you require to be edited using the Dialog Box.
This means you can edit any of the fields pertaining to a single record of data and apply it
to a template so that the same format is applied for all the other records that you will edit
later.
Dialog
Specifies the GridEditMode
EditMode If AllowEditing NA
Edit mode DialogTe
(Enum) is set to True,
mplate
the EditMode
property is
enabled.
Height—
Specifies the
height of the
dialog.
Width—
Specifies the
Width of the
dialog.
Resizable—
Specifies
Depends on whether the
Dialog dialog is
This property EditMode—
related resizable.
contains all values
the dialog Syncfusion.Mv Draggable—
(depends
Dialog c.Tools.Dialog If EditMode is Specifies
related on the
Model set to True, whether the
properties sub-
the Dialog dialog can be
properties
property is dragged or not.
used)
enabled.
MaxHeigh—
Specifies the
maximum
height of the
dialog box.
MaxWidth—
Specifies the
minimum width
of the dialog
box.
MinHeight—
Depends on
EditMode—
Specifies the
name of the If DialogMode
DialogModeE Template in is set to
string Any string DialogTempla NA
ditorTemplate the Dialog
Template te then
mode DialogModeE
ditorTemplate
is enabled.
Events
<head runat="server">
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server"
/></title>
………
<script src="<%=
Url.Content("~/Scripts/MicrosoftMvcValidation.debug.js") %>"
type="text/javascript"></script>
</head>
[_Layout.cshtml]
<head runat="server">
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server"
/></title>
………
<script
src="@Url.Content("~/Scripts/MicrosoftMvcValidation.debug.js ")"
type="text/javascript"></script>
</head>
Note: Add the following script files when the UnobtrusiveJavaScriptEnabled is true in
web.config file.
[Web.config]
<configuration>
<appSettings>
<add key='UnobtrusiveJavaScriptEnabled' value='true'/>
</appSettings>
[_Layout.cshtml]
<head>
. . . .
. . . .
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")"
type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")"
type="text/javascript"></script>
<script
src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"
type="text/javascript"></script>
</head>
[Site.Master]
<head runat="server">
. . . .
. . . .
<script src="<%=Url.Content("~/Scripts/jquery.unobtrusive-
ajax.min.js")%>" type="text/javascript"></script>
<script src="<%=Url.Content("~/Scripts/jquery.validate.min.js")%>"
type="text/javascript"></script>
<script
src="<%=Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")%
>" type="text/javascript"></script>
</head>
View[ASPX]
<%=Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model)
.Caption("Orders")
.Column(column =>
{
column.Add(p =>
p.OrderID).HeaderText("Order ID");
column.Add(p =>
p.CustomerID).HeaderText("Customer ID");
column.Add(p =>
p.ShipCountry).HeaderText("Ship
Country").CellEditType(CellEditType.DropdownEdit);
column.Add(p =>
p.OrderDate).HeaderText("Order Date").Format("{0:MM/dd/yyyy}");
column.Add(p =>
p.Freight).HeaderText("Freight").Format("{0:C}");
column.Add(p =>
p.Delivered).HeaderText("Delivered");
})
%>
View[cshtml]
@{ Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model)
.Caption("Orders")
.Column(column =>
{
column.Add(p =>
p.OrderID).HeaderText("Order ID");
column.Add(p =>
p.CustomerID).HeaderText("Customer ID");
column.Add(p =>
p.ShipCountry).HeaderText("Ship
Country").CellEditType(CellEditType.DropdownEdit);
column.Add(p =>
p.OrderDate).HeaderText("Order Date").Format("{0:MM/dd/yyyy}");
column.Add(p =>
p.Freight).HeaderText("Freight").Format("{0:C}");
column.Add(p =>
p.Delivered).HeaderText("Delivered");
})
.Render();
}
5. Enable Dialog editing mode by setting the edit mode to Dialog and configure the dialog and
editing properties such as allow new, allow edit, and allow delete, as displayed below:
View[ASPX]
<%=Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Editing( edit=>{
edit.Dialog(dialog =>
{
dialog.Height(500);
dialog.Width(460);
dialog.Position(DialogPositions.Center);
dialog.Show(DialogAnimations.bounce);
dialog.Hide(DialogAnimations.fold);
});
edit.AllowEdit(true, "Home/OrderSave")// Specify
the controller and action method which will perform the update
action.
.AllowNew(true, "Home/AddOrder")// Specify the
controller and action method which will perform the insert
action.
.AllowDelete(true, "Home/DeleteOrder");// Specify
the controller and action method which will perform the Delete
action.
})
%>
View[cshtml]
@{ Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Editing( edit=>{
edit.Dialog(dialog =>
{
dialog.Height(500);
dialog.Width(460);
dialog.Position(DialogPositions.Center);
dialog.Show(DialogAnimations.bounce);
dialog.Hide(DialogAnimations.fold);
});
Note: If you want to specify the URL in the AllowEdit property itself, specify the controller and
the corresponding action name as a URL. If you using the Mappers property then there is no need to
specify the controller name.
6. Grid allows adding new records through grid toolbar items. In this example, AddNew, Edit,
Delete, Save, and Cancel buttons have been added in the toolbar items. Therefore,
configure the toolbar as displayed below:
View[ASPX]
<%=Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model)
.ToolBar(tools =>
{
tools.Add(GridToolBarItems.AddNew)// Toolbar item for inserting
records.
.Add(GridToolBarItems.Edit) )// Toolbar item for editing
records.
.Add(GridToolBarItems.Delete)// Toolbar item for deleting
records.
.Add(GridToolBarItems.Update)// Toolbar item for saving
changes.
.Add(GridToolBarItems.Cancel);// Toolbar item for canceling
request.
})
%>
View[cshtml]
@{ Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model)
.ToolBar(tools =>
{
tools.Add(GridToolBarItems.AddNew)// Toolbar item for inserting
records.
7. Specify the primary property which uniquely identifies the grid record.
41.
View[ASPX]
<%=Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Editing( edit=>{
View[Razor]
@{ Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Editing( edit=>{
8. In the controller, create a method to add new records to grid, as displayed below. In this
example, the repository method Add() is being created to insert records to the database.
Refer the repository action method displayed below.
Controller
/// <summary>
/// Used to insert the record into the database and refresh the grid.
/// </summary>
/// <param name="ord">Editable order.</param>
/// <returns>HtmlActionResult returns the data displayed in the
grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddOrder(EditableOrder ord)
{
// Repository action method Add() is used to insert records in the data
source.
OrderRepository.Add(ord);
// After adding the record into the database, refresh the grid.
var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}
In this example, the repository method Update() is used to update records to the data source.
Controller
/// Used to insert the record into database and refresh the grid.
/// </summary>
/// <param name="ord">Editable order.</param>
/// <returns>HtmlActionResult returns the data is displayed in the
grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult OrderSave(EditableOrder ord)
{
// Repository action method Update() is used to update the records in
the data source.
OrderRepository.Update(ord);
// After saving the records to the data source, refresh the grid.
var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}
10. In the controller, create a method to delete the records from the database as displayed
below.
In this example, the repository action Delete() will delete the record from the data source.
Controller
/// <summary>
/// Used to delete the records from the data source and refresh the
grid.
/// </summary>
/// <param name="OrderID">Primary key values.</param>
/// <returns>HtmlActionResult returns the data displayed in the
grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult DeleteOrder(int OrderID)
{
// Repository action Delete() deletes the given primary value record
from the data source.
OrderRepository.Delete(OrderID);
// After deleting, refresh the grid.
var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}
11. Run the application and double click any record to edit. The grid will appear as displayed
below.
<head runat="server">
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server"
/></title>
………
<script src="<%=
Url.Content("~/Scripts/MicrosoftMvcValidation.debug.js") %>"
type="text/javascript"></script>
</head>
[_Layout.cshtml]
<head runat="server">
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server"
/></title>
………
<script
src="@Url.Content("~/Scripts/MicrosoftMvcValidation.debug.js ")"
type="text/javascript"></script>
</head>
Note: Add the following script files when the UnobtrusiveJavaScriptEnabled is true in
web.config file.
[Web.config]
<configuration>
<appSettings>
<add key='UnobtrusiveJavaScriptEnabled' value='true'/>
</appSettings>
[_Layout.cshtml]
<head>
. . . .
. . . .
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")"
type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")"
type="text/javascript"></script>
<script
src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"
type="text/javascript"></script>
</head>
[Site.Master]
<head runat="server">
. . . .
. . . .
<script src="<%=Url.Content("~/Scripts/jquery.unobtrusive-
ajax.min.js")%>" type="text/javascript"></script>
<script src="<%=Url.Content("~/Scripts/jquery.validate.min.js")%>"
type="text/javascript"></script>
<script
src="<%=Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")%
>" type="text/javascript"></script>
</head>
View[ASPX]
})%>
View[cshtml]
5. Create a GridPropertiesModel in the Index method and assign the grid properties in the
model.
Controller
ViewData["GridModel"] = model;
6. Enable editing by using the Editing property in the GridPropertiesModel and configure the
editing properties such as AllowNew, AllowEdit, and AllowDelete, as displayed below.
Controller
// Create an object for grid editing and enable the edit, add
new, and delete actions.
GridEditing edit = new GridEditing() { AllowEdit = true, AllowDelete =
true, AllowNew = true };
// Set the action mappers for the insert, delete, and save actions.
edit.DeleteMapper = "DeleteOrder";
edit.InsertMapper = "AddOrder";
edit.GridSaveMapper = "OrderSave";
Controller
// Set the Edit mode.
edit.EditMode = GridEditMode.Dialog;
9. Specify the primary property which uniquely identifies the grid record.
Controller
// Add the PrimaryKey value to uniquely identify the record.
edit.PrimaryKey = new List<string>() { "OrderID" };
42.
43. Essential Grid allows adding new records through grid toolbar items. In this example,
AddNew, Edit, Delete, Save, and Cancel buttons have been added as toolbar items as
displayed below:
Controller
// Configure the toolbar.
ToolbarSettings toolbar = new ToolbarSettings();
toolbar.Enable = true;
// Add the AddNew, Edit, Delete, Save, and Cancel buttons to the
toolbar.
toolbar.Items.Add(new ToolbarOptions() { ItemType=
GridToolBarItems.AddNew});
toolbar.Items.Add(new ToolbarOptions() { ItemType =
GridToolBarItems.Edit });
toolbar.Items.Add(new ToolbarOptions() { ItemType =
GridToolBarItems.Delete });
toolbar.Items.Add(new ToolbarOptions() { ItemType =
GridToolBarItems.Update });
toolbar.Items.Add(new ToolbarOptions() { ItemType =
GridToolBarItems.Cancel });
model.ToolBar = toolbar;
11. In the controller, create a method to add new records to grid, as displayed below. In this
example, the repository method Add() is being created to insert records in the database.
Refer to the repository action method displayed below.
Controller
/// <summary>
/// Used to insert the record in the database and refresh the grid.
/// </summary>
In this example, the repository method Update() is used to update records to the data source:
Controller
/// Used to insert the record in the database and refresh the grid.
/// </summary>
/// <param name="ord">Editable order.</param>
/// <returns>HtmlActionResult returns the data displayed in the
grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult OrderSave(EditableOrder ord)
{
// Repository action method Update is used to update the records into
datasource.
OrderRepository.Update(ord);
//After saving the records into datasource refresh the grid.
var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}
13. In the controller, create a method to delete the records from the database as displayed
below.
In this example, the repository action Delete() will delete the record from the data source.
Controller
/// <summary>
/// Used to delete records from the data source and refresh the grid.
/// </summary>
/// <param name="OrderID">Primary key values.</param>
/// <returns>HtmlActionResult returns the data displayed in the
grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
14. Run the application. The grid will appear as displayed below.
View[ASPX]
<%=Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model)
.Editing( edit=>{
edit.EditMode(GridEditMode.Dialog);// Specify the grid edit
mode.
})%>
View[cshtml]
@{ Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model)
.Editing( edit=>{
edit.EditMode(GridEditMode.Dialog);// Specify the grid edit
mode.
}).Render();
The grid will appear in the dialog editing mode as displayed below:
If you want to use the DialogTemplate mode, follow the steps displayed below.
1. Create the template in partial view, as displayed below
View[ASPX]
<fieldset>
<legend>Fields</legend>
<div class="tablediv">
<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">
<%= Html.Syncfusion().LabelFor(model
=> model.OrderID) %>
</div>
<div class="editor-field">
<%=
Html.Syncfusion().TextBoxFor(model => model.OrderID) %>
<%=
Html.Syncfusion().ValidationMessageFor(model =>
model.OrderID) %>
</div>
</div>
<div class="celldiv" style="height: auto">
<div class="editor-label">
<%= Html.Syncfusion().LabelFor(model
=> model.CustomerID) %>
</div>
<div class="editor-field">
<%=
Html.Syncfusion().TextBoxFor(model => model.CustomerID)
%>
<%=
Html.Syncfusion().ValidationMessageFor(model =>
model.CustomerID) %>
</div>
</div>
</div>
<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">
<%= Html.Syncfusion().LabelFor(model
=> model.EmployeeID) %>
</div>
<div class="editor-field">
<%=
Html.Syncfusion().TextBoxFor(model => model.EmployeeID)
%>
<%=
Html.Syncfusion().ValidationMessageFor(model =>
model.EmployeeID) %>
</div>
</div>
<div class="celldiv" style="height: auto">
<div class="editor-label">
<%= Html.Syncfusion().LabelFor(model
=> model.ShipName) %>
</div>
<div class="editor-field">
<%=
Html.Syncfusion().TextBoxFor(model => model.ShipName) %>
<%=
Html.Syncfusion().ValidationMessageFor(model =>
model.ShipName) %>
</div>
</div>
</div>
<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">
<%= Html.Syncfusion().LabelFor(model
=> model.ShipAddress) %>
</div>
<div class="editor-field">
<%=
Html.Syncfusion().TextBoxFor(model => model.ShipAddress)
%>
<%=
Html.Syncfusion().ValidationMessageFor(model =>
model.ShipAddress) %>
</div>
</div>
<div class="celldiv" style="height: auto">
<div class="editor-label">
<%= Html.Syncfusion().LabelFor(model
=> model.ShipCity) %>
</div>
<div class="editor-field">
<%=
Html.Syncfusion().TextBoxFor(model => model.ShipCity) %>
<%=
Html.Syncfusion().ValidationMessageFor(model =>
model.ShipCity) %>
</div>
</div>
</div>
<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">
<%= Html.Syncfusion().LabelFor(model
=> model.ShipRegion) %>
</div>
<div class="editor-field">
<%=
Html.Syncfusion().TextBoxFor(model => model.ShipRegion)
%>
<%=
Html.Syncfusion().ValidationMessageFor(model =>
model.ShipRegion) %>
</div>
</div>
<div class="celldiv" style="height: auto">
<div class="editor-label">
<%= Html.Syncfusion().LabelFor(model
=> model.ShipCountry) %>
</div>
<div class="editor-field">
<%=
Html.Syncfusion().TextBoxFor(model => model.ShipCountry)
%>
<%=
Html.Syncfusion().ValidationMessageFor(model =>
model.ShipCountry) %>
</div>
</div>
</div>
<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">
<%= Html.Syncfusion().LabelFor(model
=> model.Freight) %>
</div>
<div class="editor-field">
<%=
Html.Syncfusion().TextBoxFor(model => model.Freight) %>
<%=
Html.Syncfusion().ValidationMessageFor(model =>
model.Freight) %>
</div>
</div>
<div class="celldiv" style="height: auto">
<div class="editor-label">
<%= Html.Syncfusion().LabelFor(model
=> model.OrderDate) %>
</div>
<div class="editor-field">
<%=
Html.Syncfusion().TextBoxFor(model => model.OrderDate,
String.Format("{0:g}", Model.OrderDate)) %>
<%=
Html.Syncfusion().ValidationMessageFor(model =>
model.OrderDate) %>
</div>
</div>
</div>
</div>
</fieldset>
View [Razor]
<fieldset>
<legend>Fields</legend>
<div class="tablediv">
<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model => model.OrderID)
</div>
<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model =>
model.OrderID)
@Html.Syncfusion().ValidationMessageFor(model =>
model.OrderID)
</div>
</div>
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model =>
model.CustomerID)
</div>
<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model =>
model.CustomerID)
@Html.Syncfusion().ValidationMessageFor(model =>
model.CustomerID)
</div>
</div>
</div>
<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model =>
model.EmployeeID)
</div>
<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model =>
model.EmployeeID)
@ Html.Syncfusion().ValidationMessageFor(model =>
model.EmployeeID)
</div>
</div>
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model =>
model.ShipName)
</div>
<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model =>
model.ShipName)
@Html.Syncfusion().ValidationMessageFor(model =>
model.ShipName)
</div>
</div>
</div>
<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model =>
model.ShipAddress)
</div>
<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model =>
model.ShipAddress)
@Html.Syncfusion().ValidationMessageFor(model =>
model.ShipAddress)
</div>
</div>
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model => model.ShipCity)
</div>
<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model =>
model.ShipCity)
@ Html.Syncfusion().ValidationMessageFor(model =>
model.ShipCity)
</div>
</div>
</div>
<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model =>
model.ShipRegion)
</div>
<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model =>
model.ShipRegion)
@ Html.Syncfusion().ValidationMessageFor(model =>
model.ShipRegion)
</div>
</div>
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model =>
model.ShipCountry)
</div>
<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model
=>model.ShipCountry)
@Html.Syncfusion().ValidationMessageFor(model =>
model.ShipCountry)
</div>
</div>
</div>
<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model => model.Freight)
</div>
<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model =>
model.Freight)
@Html.Syncfusion().ValidationMessageFor(model =>
model.Freight)
</div>
</div>
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model =>
model.OrderDate)
</div>
<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model =>
model.OrderDate,String.Format("{0:g}", Model.OrderDate))
@Html.Syncfusion().ValidationMessageFor(model =>
model.OrderDate)
</div>
</div>
</div>
</div>
</fieldset>
Note: Don’t specify the form in the template. And the <fieldset> tag is required to surround the
template input fields else the buttons will not be displayed by the dialog.
44.
45. Configure the GridEditMode as DialogTemplate Mode and specify the name of the partial
view which contains the templates, as displayed below:
View[ASPX]
<%=Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model)
.Editing( edit=>{
edit.DialogModeEditorTemplate("OrderEditorTemplate");
edit.EditMode(GridEditMode.DialogTemplate);// Specify the grid
edit mode.
})%>
View[cshtml]
@{ Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model)
.Editing( edit=>{
edit.DialogModeEditorTemplate("OrderEditorTemplate");
}).Render();
46. In the DialogTemplate mode, you should handle the insert action and the edit action.
To achieve this, check the RequestType property from PagingParams. If the request type is
either BeginEdit or BeginAddNew, then render the template by using the PartialView() method,
as displayed below.
Controller
/// <summary>
/// Paging and editing requests are mapped to
this method. This method invokes the HtmlActionResult
/// from the grid. The required response is
generated.
/// </summary>
/// <param name="args">Contains paging
properties. </param>
/// <returns>
/// HtmlActionResult returns the data displayed
in the grid.
/// </returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args
,int? OrderID)
{
RequestType currentRequest =
(RequestType)Convert.ToInt32(args.RequestType);
// Check if the current request is an Edit
request and the edit mode is TemplateForm mode. Then
call the PartialView() to render the template.
if (currentRequest == RequestType.BeginEdit)
{
EditableOrder ord =
(EditableOrder)OrderRepository.Select(OrderID);
return
PartialView("OrderEditorTemplate", ord);
}
else if (currentRequest ==
RequestType.BeginAddNew)
{
// Check if the current request is an
AddNew request and edit mode is TemplateForm mode. Then
47. The grid will appear in the dialog template editing mode as displayed below:
Sample Link
To view the samples, follow the steps below:
1. Open the Grid sample browser from the dashboard (Refer to the Samples and Location
chapter).
2. Navigate to Grid.MVC > Editing > Dialog Editing
You can position the edit form either in the top-right corner (by default), bottom-left left corner of
the Grid; or in a custom location, using a target ID, if you choose.
Use Case Scenario
This feature allows you to view the data you edit more clearly, while offering an uncompromised
view of the other data entries in the grid.
Appearance and Structure
The following figures illustrate the appearance and structure of the ExternalForm EditMode
feature, and its settings:
Figure 140: External Form Edit Mode with External Form in the top-right of the Grid
Figure 142: External Form Edit Mode with Customized Template (Custom Fields in Grid)
If you have a customized template that you would like to use for the external edit form, this
feature allows you to use it. You may have new fields and customized dimensions that you can
use for the edit form.
Figure 143: External Edit Form with Custom Position (Target ID)
When you set the target ID for the ExternalForm EditMode, you will not only be able to customize
the position of the edit form, but also the skin used.
The target ID (of the element in the page) allows you to place the edit form anywhere on the
same page as the grid. If in case the element doesn’t exist on the page, you will not be able to
place the edit form in that location.
Note: The custom skin of your edit form template is not overridden by the default skin used by
the edit form, if you choose this option.
4.7.7.1 Properties
Type of
Property Description Value it accepts Dependencies
property
Depends on
AllowEditing—
GridEditMode ExternalForm
EditMode Specifies the Edit Mode
(Enum) ExternalFormTemplate If AllowEditing is set to
True, the EditMode
property is enabled.
Depends on
Position.TopRight, ExternalForm—
Specifies position of the
Position Enum Position.BottomLeft,
external form
Position.Custom If GridEditMode is
External Form, position
View[ASPX]
<head runat="server">
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server"
/></title>
………
<script src="<%=
Url.Content("~/Scripts/MicrosoftMvcValidation.debug.js") %>"
type="text/javascript"></script>
</head>
48.
[_Layout.cshtml]
<head runat="server">
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server"
/></title>
………
<script
src="@Url.Content("~/Scripts/MicrosoftMvcValidation.debug.js ")"
type="text/javascript"></script>
</head>
49.
Note: Add the following script files when the UnobtrusiveJavaScriptEnabled is true in
web.config file.
[Web.config]
<configuration>
<appSettings>
<add key='UnobtrusiveJavaScriptEnabled' value='true'/>
</appSettings>
[_Layout.cshtml]
<head>
. . . .
. . . .
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")"
type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")"
type="text/javascript"></script>
<script
src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"
type="text/javascript"></script>
</head>
[Site.Master]
<head runat="server">
. . . .
. . . .
<script src="<%=Url.Content("~/Scripts/jquery.unobtrusive-
ajax.min.js")%>" type="text/javascript"></script>
<script src="<%=Url.Content("~/Scripts/jquery.validate.min.js")%>"
type="text/javascript"></script>
<script
src="<%=Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")%
>" type="text/javascript"></script>
</head>
1. In the view, use the Model property in the Datasource() to bind the data source.
View[ASPX]
<%=Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model).ActionMode(ActionMode.JSON)
.Caption("Orders")
---------
.Column(column =>
{
})
----------
%>
50.
View [cshtml]
@{Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model).ActionMode(ActionMode.JSON)
.Caption("Orders")
----------
.Column(column =>
{
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.CustomerID).HeaderText("Customer ID");
column.Add(p => p.ShipCountry).HeaderText("Ship Country");
column.Add(p => p.OrderDate).HeaderText("Order Date");
column.Add(p => p.Freight).HeaderText("Freight");
})
----------
51.
52.
2. Essential Grid allows adding new records through grid toolbar items.
53.
In this example, AddNew, Edit, Delete, Save, and Cancel buttons have been added in the
toolbar items, as displayed below.
View[ASPX]
<%=Html.Syncfusion().Grid<EditableOrder>("Grid1")
-------
.ToolBar(tools =>
{
tools.Add(GridToolBarItems.AddNew)// Toolbar item for
inserting records.
.Add(GridToolBarItems.Edit)// Toolbar item for
editing records.
View[cshtml]
@{Html.Syncfusion().Grid<EditableOrder>("Grid1")
-------
.ToolBar(tools =>
{
tools.Add(GridToolBarItems.AddNew)// Toolbar item for
inserting records.
.Add(GridToolBarItems.Edit)// Toolbar item for
editing records.
.Add(GridToolBarItems.Delete)// Toolbar item for
deleting records.
.Add(GridToolBarItems.Update)// Toolbar item for
saving changes.
.Add(GridToolBarItems.Cancel);// Toolbar item for
canceling request.
})
----------
}
3. Enable ExternalForm editing by using the Editing property and its sub-properties, as
displayed below.
54.
View[ASPX]
<%=Html.Syncfusion().Grid<EditableOrder>("Grid1")
-------
.Editing(edit=>{
edit.ExternalForm(ef =>
{
ef.TargetID("ExternalEditForm");
ef.Position(ExternalFormPosition.TopRight);
});
55.
56.
View[cshtml]
@{Html.Syncfusion().Grid<EditableOrder>("Grid1")
-------
.Editing(edit=>{
edit.ExternalForm(ef =>
{
ef.TargetID("ExternalEditForm");
ef.Position(ExternalFormPosition.TopRight);
});
// Specify the controller and action method which will
perform the update action.
edit.AllowEdit(true, "Home/OrderSave")
// Specify the controller and action method which will
perform the insert action.
.AllowNew(true, "Home/AddOrder")
// Specify the controller and action method which will
perform the delete action.
.AllowDelete(true, "Home/DeleteOrder");
// Specify the grid edit mode.
edit.EditMode(GridEditMode.ExternalForm);
edit.ExternalModeEditorTemplate("OrderEditorTemplate");
// Add primary key to primary key collections.
edit.PrimaryKey(key => key.Add(p => p.OrderID));
})
--------
}
Note: If you want to specify the URL in the AllowEdit property itself means, specify the controller
and the corresponding action name as a URL. If you using the Mappers property then there is no
need to specify the controller name.
Controller
/// <summary>
/// Used for rendering the grid initially.
/// </summary>
/// <returns>View page; it displays the grid.</returns>
public ActionResult ExternalFormEdit()
{
return View(OrderRepository.GetAllRecords());
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult ExternalFormEdit(PagingParams args, int? OrderID,
GridEditMode? GridMode)
{
RequestType currentRequest =
(RequestType)Convert.ToInt32(args.RequestType);
if (currentRequest == RequestType.BeginEdit && GridMode ==
GridEditMode.ExternalFormTemplate)
{
EditableOrder ord = (EditableOrder)OrderRepository.Select(OrderID);
}
}
View[ASPX]
<head runat="server">
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server"
/></title>
………
<script src="<%=
Url.Content("~/Scripts/MicrosoftMvcValidation.debug.js") %>"
type="text/javascript"></script>
</head>
[_Layout.cshtml]
<head runat="server">
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server"
/></title>
………
<script
src="@Url.Content("~/Scripts/MicrosoftMvcValidation.debug.js ")"
type="text/javascript"></script>
</head>
Note: Add the following script files when the UnobtrusiveJavaScriptEnabled is true in
web.config file.
[Web.config]
<configuration>
<appSettings>
<add key='UnobtrusiveJavaScriptEnabled' value='true'/>
</appSettings>
[_Layout.cshtml]
<head>
. . . .
. . . .
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")"
type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")"
type="text/javascript"></script>
<script
src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"
type="text/javascript"></script>
</head>
[Site.Master]
<head runat="server">
. . . .
. . . .
<script src="<%=Url.Content("~/Scripts/jquery.unobtrusive-
ajax.min.js")%>" type="text/javascript"></script>
<script src="<%=Url.Content("~/Scripts/jquery.validate.min.js")%>"
type="text/javascript"></script>
<script
src="<%=Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")%
>" type="text/javascript"></script>
</head>
View[ASPX]
<%=Html.Syncfusion().Grid<EditableOrder>(
"Grid1", "GridModel",
column =>
{
column.Add(p => p.OrderID).HeaderText("Order
ID");
column.Add(p =>
p.CustomerID).HeaderText("Customer ID");
column.Add(p =>
p.ShipCountry).HeaderText("Ship Country");
column.Add(p =>
p.OrderDate).HeaderText("Order Date");
column.Add(p =>
p.Freight).HeaderText("Freight");
})
%>
View[cshtml]
@{Html.Syncfusion().Grid<EditableOrder>(
"Grid1", "GridModel",
column =>
{
column.Add(p => p.OrderID).HeaderText("Order
ID");
column.Add(p =>
p.CustomerID).HeaderText("Customer ID");
column.Add(p =>
p.ShipCountry).HeaderText("Ship Country");
column.Add(p =>
p.OrderDate).HeaderText("Order Date");
column.Add(p =>
p.Freight).HeaderText("Freight");
}).Render();
}
5. Create a GridPropertiesModel in the Index method and assign the grid properties in the
model.
57.
Controller
ViewData["GridModel"] = gridModel;
6. Essential Grid allows adding new records through grid toolbar items.
58.
In this example, AddNew, Edit, Delete, Save, and Cancel buttons have been added in the
toolbar items, as displayed below.
Controller
edit.GridSaveMapper = "OrderSave";
edit.ExternalModeEditorTemplate = "OrderEditorTemplate";
edit.ExternalForm.Position = position == null ?
ExternalFormPosition.TopRight : (ExternalFormPosition)position;
edit.ExternalForm.TargetID = "ExternalFormEdit";
edit.EditMode = GridMode == null ? GridEditMode.ExternalForm :
(GridEditMode)GridMode;
edit.PrimaryKey = new List<string>() { "OrderID" };
gridModel.Editing = edit;
7. Enable editing by using the External form Editing property in the GridPropertiesModel
and configure the editing properties such as allow new, allow edit, and allow delete, as
displayed below
59.
Controller
Controller
AllowScrolling = false,
AllowFiltering = true,
Height = 225,
AutoFormat = Skins.Sandune,
ActionMode = ActionMode.JSON,
};
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult ExternalFormEditJsonModel(PagingParams args, int?
OrderID, GridEditMode? GridMode)
{
RequestType currentRequest =
(RequestType)Convert.ToInt32(args.RequestType);
if (currentRequest == RequestType.BeginEdit && GridMode ==
GridEditMode.ExternalFormTemplate)
{
EditableOrder ord = (EditableOrder)OrderRepository.Select(OrderID);
Commands properties:
Events
Event Description Arguments Type Reference links
4.7.8.2 Appearance
1. Open the Grid sample browser from the dashboard (Refer to the Samples and Location
chapter).
2. Navigate to Grid.MVC > Editing > Unbound Column Editing
2. Through GridPropertiesModel
View[ASPX]
<head runat="server">
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server"
/></title>
………
<script src="<%=
Url.Content("~/Scripts/MicrosoftMvcValidation.debug.js") %>"
type="text/javascript"></script>
</head>
[_Layout.cshtml]
<head runat="server">
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server"
/></title>
………
<script
src="@Url.Content("~/Scripts/MicrosoftMvcValidation.debug.js ")"
type="text/javascript"></script>
</head>
Note: Add the following script files when the UnobtrusiveJavaScriptEnabled is true in
web.config file.
[Web.config]
<configuration>
<appSettings>
<add key='UnobtrusiveJavaScriptEnabled' value='true'/>
</appSettings>
[_Layout.cshtml]
<head>
. . . .
. . . .
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")"
type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")"
type="text/javascript"></script>
<script
src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"
type="text/javascript"></script>
</head>
[Site.Master]
<head runat="server">
. . . .
. . . .
<script src="<%=Url.Content("~/Scripts/jquery.unobtrusive-
ajax.min.js")%>" type="text/javascript"></script>
<script src="<%=Url.Content("~/Scripts/jquery.validate.min.js")%>"
type="text/javascript"></script>
<script
src="<%=Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")%
>" type="text/javascript"></script>
</head>
View[ASPX]
<%=Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model)
.Caption("Orders")
.Column(column =>
{
column.Add(p =>
p.OrderID).HeaderText("Order ID");
column.Add(p =>
p.CustomerID).HeaderText("Customer ID");
column.Add(p =>
p.ShipCountry).HeaderText("Ship
Country").CellEditType(CellEditType.DropdownEdit);
column.Add(p =>
p.OrderDate).HeaderText("Order Date").Format("{0:MM/dd/yyyy}");
column.Add(p =>
p.Freight).HeaderText("Freight").Format("{0:C}");
column.Add(p =>
p.Delivered).HeaderText("Delivered");
})
%>
View[cshtml]
@{ Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model)
.Caption("Orders")
.Column(column =>
{
column.Add(p =>
p.OrderID).HeaderText("Order ID");
column.Add(p =>
p.CustomerID).HeaderText("Customer ID");
column.Add(p =>
p.ShipCountry).HeaderText("Ship
Country").CellEditType(CellEditType.DropdownEdit);
column.Add(p =>
p.OrderDate).HeaderText("Order Date").Format("{0:MM/dd/yyyy}");
column.Add(p =>
p.Freight).HeaderText("Freight").Format("{0:C}");
column.Add(p =>
p.Delivered).HeaderText("Delivered");
})
.Render();
}
5. Enable the editing mode by setting the edit mode to Normal and configure the editing
properties such as allow New, Allow Edit, and Allow Delete as displayed below:
View[ASPX]
<%=Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Editing( edit=>{
edit.AllowEdit(true, "Home/OrderSave")// Specify
the controller and action method which will perform the update
action.
.AllowNew(true, "Home/AddOrder")// Specify the
controller and action method which will perform the insert
action.
.AllowDelete(true, "Home/DeleteOrder");// Specify
the controller and action method which will perform the delete
action.
})
%>
View[cshtml]
@( Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Editing( edit=>{
edit.AllowEdit(true, "Home/OrderSave")// Specify
the controller and action method which will perform the update
action.
.AllowNew(true, "Home/AddOrder")// Specify the
controller and action method which will perform the insert
action.
.AllowDelete(true, "Home/DeleteOrder");// Specify
the controller and action method which will perform the delete
action.
})
)
Note: If you want to specify the URL in the AllowEdit property itself means, specify the
controller and the corresponding action name as a URL. If you using the Mappers property then
there is no need to specify the controller name.
6. Essential Grid allows editing and deleting records through grid unbound column items. In this
example, AddNew, Edit, Delete, Save, and Cancel buttons have been added in the toolbar
items. Therefore, configure the toolbar as displayed below:
View[ASPX]
<%=Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model)
.column.Add("ManageRecords", col =>
{
// Unbound column for editing records.
col.Commands(cmd =>
{
cmd.Command(CommandTypes.Edit).Text("Edit").ImageUrl("/Content/Edit.png
").ItemType(UnBoundItemTypes.Button).ItemOption(UnboundItemOptions.Imag
eOnly);
});
// Unbound column for updating records.
col.Commands(cmd =>
{
cmd.Command(CommandTypes.Update).Text("Update").ImageUrl("/Content/Upda
te.png").ItemType(UnBoundItemTypes.HyperLink).ItemOption(UnboundItemOpt
ions.ImagePlusText);
});
// Unbound column for deleting records.
col.Commands(cmd1 =>
{
cmd1.Command(CommandTypes.Delete).Text("Delete").ImageUrl("/Content/Del
ete.png").ItemType(UnBoundItemTypes.Button).ItemOption(UnboundItemOptio
ns.TextOnly);
});
col.Commands(command =>
{
command.Command(CommandTypes.Custom)
.ItemType(UnBoundItemTypes.Button)
.ItemOption(UnboundItemOptions.TextOnly)
.Mapper("ViewDetails?Orderid={OrderID}")
.Text("View");
});
}).UnBound(true); // Unbound must be true
to make it an unbound column.
})
%>
View[cshtml]
@( Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model)
.column.Add("ManageRecords", col =>
{
// Unbound column for editing records.
col.Commands(cmd =>
{
cmd.Command(CommandTypes.Edit).Text("Edit").ImageUrl("/Content/Edit.png
").ItemType(UnBoundItemTypes.Button).ItemOption(UnboundItemOptions.Imag
eOnly);
});
// Unbound column for updating records.
col.Commands(cmd =>
{
cmd.Command(CommandTypes.Update).Text("Update").ImageUrl("/Content/Upda
te.png").ItemType(UnBoundItemTypes.HyperLink).ItemOption(UnboundItemOpt
ions.ImagePlusText);
});
// Unbound column for deleting records.
col.Commands(cmd1 =>
{
cmd1.Command(CommandTypes.Delete).Text("Delete").ImageUrl("/Content/Del
ete.png").ItemType(UnBoundItemTypes.Button).ItemOption(UnboundItemOptio
ns.TextOnly);
});
col.Commands(command =>
{
command.Command(CommandTypes.Custom)
.ItemType(UnBoundItemTypes.Button)
.ItemOption(UnboundItemOptions.TextOnly)
.Mapper("ViewDetails?Orderid={OrderID}")
.Text("View");
});
})
Note: The Mapper action Command can be used in an unbound column for command type as
Custom only. If we define the mapper for defined commands like Edit, Save, Cancel, Insert there will
be unnecessary conflict between the grid mappers for editing actions and mapper defined for
commands. To avoid this type of conflict, use the Unbound Mapper action for Custom command
only.
7. Specify the primary property which uniquely identifies the grid record.
View[ASPX]
<%=Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Editing( edit=>{
View[cshtml]
@{ Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Editing( edit=>{
8. In the controller, create a method to add new records to grid as displayed below. In this
example, the repository method Add() is being created to insert records to the database.
Refer to the repository action method displayed below.
Controller
/// <summary>
/// Used to insert the record into the database and refresh the grid.
/// </summary>
/// <param name="ord">Editable order.</param>
/// <returns>HtmlActionResult returns the data displayed in the
grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddOrder(EditableOrder ord)
{
// Repository action method Add() is used to insert records in the data
source.
OrderRepository.Add(ord);
// After adding the record into the database, refresh the grid.
var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}
In this example, the repository method Update() is used to update records to the data source.
Controller
/// Used to insert the record into database and refresh the grid.
/// </summary>
/// <param name="ord">Editable order.</param>
/// <returns>HtmlActionResult returns the data is displayed in the
grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult OrderSave(EditableOrder ord)
{
// Repository action method Update() is used to update the records in
the data source.
OrderRepository.Update(ord);
// After saving the records to the data source, refresh the grid.
var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}
10. In the controller, create a method to delete the records from the database as displayed
below.
In this example, the repository action Delete() will delete the record from the data source.
Controller
/// <summary>
/// Used to delete the records from the data source and refresh the
grid.
/// </summary>
/// <param name="OrderID">Primary key values.</param>
/// <returns>HtmlActionResult returns the data displayed in the
grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult DeleteOrder(int OrderID)
{
// Repository action Delete() deletes the given primary value record
from the data source.
OrderRepository.Delete(OrderID);
// After deleting, refresh the grid.
var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}
11. In the controller, create a method to view the records from the database as displayed below.
In this example, the repository action ViewDetails() will show the record from the data source.
Controller
12. Run the application and click the Edit button to edit the record. The grid will appear as
displayed below.
View[ASPX]
<head runat="server">
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server"
/></title>
………
<script src="<%=
Url.Content("~/Scripts/MicrosoftMvcValidation.debug.js") %>"
type="text/javascript"></script>
</head>
[_Layout.cshtml]
<head runat="server">
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server"
/></title>
………
<script
src="@Url.Content("~/Scripts/MicrosoftMvcValidation.debug.js ")"
type="text/javascript"></script>
</head>
Note: Add the following script files when the UnobtrusiveJavaScriptEnabled is true in
web.config file.
[Web.config]
<configuration>
<appSettings>
<add key='UnobtrusiveJavaScriptEnabled' value='true'/>
</appSettings>
[_Layout.cshtml]
<head>
. . . .
. . . .
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")"
type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")"
type="text/javascript"></script>
<script
src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"
type="text/javascript"></script>
</head>
[Site.Master]
<head runat="server">
. . . .
. . . .
<script src="<%=Url.Content("~/Scripts/jquery.unobtrusive-
ajax.min.js")%>" type="text/javascript"></script>
<script src="<%=Url.Content("~/Scripts/jquery.validate.min.js")%>"
type="text/javascript"></script>
<script
src="<%=Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")%
>" type="text/javascript"></script>
</head>
View[ASPX]
<%=Html.Syncfusion().Grid<EditableOrder>("Grid1",
(GridPropertiesModel<EditableOrder>)ViewData["GridModel"])%>
View[cshtml]
@(Html.Syncfusion().Grid<EditableOrder>("Grid1",
(GridPropertiesModel<EditableOrder>)ViewData["GridModel"]))
[Controller]
GridCommands<EditableOrder> cmd1 = new GridCommands<EditableOrder>()
{
ItemType = UnBoundItemTypes.Button,
ImageUrl = Url.Content("~/Content/Images/Edit.png"),
ItemOption = UnboundItemOptions.ImageOnly,
Text = "Edit",
Type = "Edit"
};
GridCommands<EditableOrder> cmd2 = new
GridCommands<EditableOrder>()
{
ItemType = UnBoundItemTypes.HyperLink,
ImageUrl = Url.Content("~/Content/Images/Update.png"),
ItemOption = UnboundItemOptions.ImagePlusText,
Text = "Update",
Type = "Update"
};
GridCommands<EditableOrder> cmd3 = new
GridCommands<EditableOrder>()
{
ItemType = UnBoundItemTypes.Button,
ImageUrl = Url.Content("~/Content/Images/Delete.png"),
ItemOption = UnboundItemOptions.TextOnly,
Text = "Delete",
Type = "Delete"
};
GridCommands<EditableOrder> cmd4 = new
GridCommands<EditableOrder>()
{
ItemType = UnBoundItemTypes.Button,
ImageUrl = Url.Content("~/Content/Images/Delete.png"),
ItemOption = UnboundItemOptions.TextOnly,
Text = "View",
Type = "Custom",
Mapper = "ViewDetails?Orderid={OrderID}"
};
List<GridCommands<EditableOrder>> commandColl = new
List<GridCommands<EditableOrder>>();
commandColl.Add(cmd1);
commandColl.Add(cmd2);
commandColl.Add(cmd3);
commandColl.Add(cmd4);
Note: We can use Mapper action Command in unbound column for command type as Custom
only. If we define the mapper for defined commands like Edit, Save, Cancel, Insert there will be
unnecessary conflict between the grid mappers for editing actions and mapper defined for
commands. To avoid this type of conflicts we suggest you to use the Unbound Mapper action for
Custom command only.
5. Create a GridPropertiesModel in the Index method and assign the grid properties in the
model.
Controller
{
DataSource = OrderRepository.GetAllRecords(),
Caption = "Orders",
AllowPaging = true,
AllowSorting = true,
AllowGrouping=true,
AutoFormat=Skins.Marble
};
model.Columns = new List<GridColumn<EditableOrder>>
{
new GridColumn<EditableOrder>
{
6. Enable editing by using the Editing property in the GridPropertiesModel and configure the
editing properties such as AllowEdit and AllowDelete as displayed below.
Controller
// Create an object for grid editing and enable the edit, add
new, and delete actions.
GridEditing edit = new GridEditing() { AllowEdit = true, AllowDelete =
true };
// Set the action mappers for the insert, delete, and save actions.
edit.DeleteMapper = "DeleteOrder";
edit.GridSaveMapper = "OrderSave";
edit.InsertMapper ="AddOrder";
Controller
// Set the Edit mode.
edit.EditMode = GridEditMode.Normal;
8. Specify the primary property which uniquely identifies the grid record.
Controller
// Add the PrimaryKey value to uniquely identify the record.
edit.PrimaryKey = new List<string>() { "OrderID" };
Controller
// Add the edit object to the model.
model.Editing = edit;
10. In the controller, create a method to add new records to the grid as displayed below. In this
example, the repository method Add() is being created to insert records to the database.
Refer to the repository action method displayed below.
Controller
/// <summary>
/// Used to insert the record into the database and refresh the grid.
/// </summary>
/// <param name="ord">Editable order.</param>
/// <returns>HtmlActionResult returns the data displayed in the
grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddOrder(EditableOrder ord)
{
// Repository action method Add() is used to insert records in the data
source.
OrderRepository.Add(ord);
// After adding the record into the database, refresh the grid.
var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}
In this example, the repository method Update() is used to update records to the data source:
Controller
/// Used to insert the record in the database and refresh the grid.
/// </summary>
/// <param name="ord">Editable order.</param>
/// <returns>HtmlActionResult returns the data displayed in the
grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult OrderSave(EditableOrder ord)
{
// Repository action method Update is used to update the records into
datasource.
OrderRepository.Update(ord);
//After saving the records into datasource refresh the grid.
var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}
12. In the controller, create a method to delete the records from the database as displayed
below.
In this example, the repository action Delete() will delete the record from the data source.
Controller
/// <summary>
/// Used to delete records from the data source and refresh the grid.
/// </summary>
/// <param name="OrderID">Primary key values.</param>
/// <returns>HtmlActionResult returns the data displayed in the
grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult DeleteOrder(int OrderID)
{
// Repository action Delete() deletes the given primary value record
from the data source.
OrderRepository.Delete(OrderID);
// After deleting, refresh the grid.
var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}
13. In the controller, create a method to view the records from the database as displayed below.
In this example, the repository action ViewDetails() will show the record from the data source.
Controller
14. Run the application. The grid will appear as displayed below.
View[ASPX]
<head runat="server">
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server"
/></title>
………
<script src="<%=
Url.Content("~/Scripts/MicrosoftMvcValidation.debug.js") %>"
type="text/javascript"></script>
</head>
[_Layout.cshtml]
<head runat="server">
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server"
/></title>
………
<script
src="@Url.Content("~/Scripts/MicrosoftMvcValidation.debug.js ")"
type="text/javascript"></script>
</head>
60.
Note: Add the following script files when the UnobtrusiveJavaScriptEnabled is true in
web.config file.
[Web.config]
<configuration>
<appSettings>
<add key='UnobtrusiveJavaScriptEnabled' value='true'/>
</appSettings>
[_Layout.cshtml]
<head>
. . . .
. . . .
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")"
type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")"
type="text/javascript"></script>
<script
src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"
type="text/javascript"></script>
</head>
[Site.Master]
<head runat="server">
. . . .
. . . .
<script src="<%=Url.Content("~/Scripts/jquery.unobtrusive-
ajax.min.js")%>" type="text/javascript"></script>
<script src="<%=Url.Content("~/Scripts/jquery.validate.min.js")%>"
type="text/javascript"></script>
<script
src="<%=Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")%
>" type="text/javascript"></script>
</head>
View[ASPX]
<%=Html.Syncfusion().Grid<EditableOrder>("Grid1")
.ActionMode(ActionMode.JSON)
.Column(column =>
{
column.Add(p =>
p.OrderID).HeaderText("Order ID");
column.Add(p =>
p.CustomerID).HeaderText("Customer ID");
column.Add(p =>
p.ShipCountry).HeaderText("Ship
Country").CellEditType(CellEditType.DropdownEdit);
column.Add(p =>
p.OrderDate).HeaderText("Order Date").Format("{0:MM/dd/yyyy}");
column.Add(p =>
p.Freight).HeaderText("Freight").Format("{0:C}");
column.Add(p =>
p.Delivered).HeaderText("Delivered");
})
%>
View[cshtml]
@{ Html.Syncfusion().Grid<EditableOrder>("Grid1")
.ActionMode(ActionMode.JSON)
.Caption("Orders")
.Column(column =>
{
column.Add(p =>
p.OrderID).HeaderText("Order ID");
column.Add(p =>
p.CustomerID).HeaderText("Customer ID");
column.Add(p =>
p.ShipCountry).HeaderText("Ship
Country").CellEditType(CellEditType.DropdownEdit);
column.Add(p =>
p.OrderDate).HeaderText("Order Date").Format("{0:MM/dd/yyyy}");
column.Add(p =>
p.Freight).HeaderText("Freight").Format("{0:C}");
column.Add(p =>
p.Delivered).HeaderText("Delivered");
})
.Render();
}
5. Enable the editing mode by setting the edit mode to Normal and configure the editing
properties such as AllowNew, AllowEdit, and AllowDelete as displayed below.
View[ASPX]
<%=Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Editing( edit=>{
edit.AllowEdit(true, "Home/OrderSave")// Specify
the controller and action method which will perform the update
action.
.AllowNew(true, "Home/AddOrder")// Specify the
controller and action method which will perform the insert
action.
.AllowDelete(true, "Home/DeleteOrder");// Specify
the controller and action method which will perform the delete
action.
})
%>
View[cshtml]
@( Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Editing( edit=>{
edit.AllowEdit(true, "Home/OrderSave")// Specify
the controller and action method which will perform the update
action.
.AllowNew(true, "Home/AddOrder")// Specify the
Note: If you want to specify the URL in the AllowEdit property itself means, specify the
controller and the corresponding action name as a URL. If you using the Mappers property then
there is no need to specify the controller name.
6. Essential Grid allows editing and deleting records through grid unbound column items. In this
example, AddNew, Edit, Delete, Save, and Cancel buttons have been added in the toolbar
items. Therefore, configure the toolbar as displayed below.
View[ASPX]
<%=Html.Syncfusion().Grid<EditableOrder>("Grid1")
.ActionMode(ActionMode.JSON)
.column.Add("ManageRecords", col =>
{
// Unbound column for editing records.
col.Commands(cmd =>
{
cmd.Command(CommandTypes.Edit).Text("Edit").ImageUrl("/Content/Edit.png
").ItemType(UnBoundItemTypes.Button).ItemOption(UnboundItemOptions.Imag
eOnly);
});
// Unbound column for updating records.
col.Commands(cmd =>
{
cmd.Command(CommandTypes.Update).Text("Update").ImageUrl("/Content/Upda
te.png").ItemType(UnBoundItemTypes.HyperLink).ItemOption(UnboundItemOpt
ions.ImagePlusText);
});
// Unbound column for deleting records.
col.Commands(cmd1 =>
{
cmd1.Command(CommandTypes.Delete).Text("Delete").ImageUrl("/Content/Del
ete.png").ItemType(UnBoundItemTypes.Button).ItemOption(UnboundItemOptio
ns.TextOnly);
});
col.Commands(command =>
{
command.Command(CommandTypes.Custom)
.ItemType(UnBoundItemTypes.Button)
.ItemOption(UnboundItemOptions.TextOnly)
.Mapper("ViewDetails?Orderid=${OrderID}")
.Text("View");
});
})
%>
View[cshtml]
@( Html.Syncfusion().Grid<EditableOrder>("Grid1")
. ActionMode(ActionMode.JSON)
col.Commands(cmd =>
{
cmd.Command(CommandTypes.Edit).Text("Edit").ImageUrl("/Content/Edit.png
").ItemType(UnBoundItemTypes.Button).ItemOption(UnboundItemOptions.Imag
eOnly);
});
// Unbound column for updating records.
col.Commands(cmd =>
{
cmd.Command(CommandTypes.Update).Text("Update").ImageUrl("/Content/Upda
te.png").ItemType(UnBoundItemTypes.HyperLink).ItemOption(UnboundItemOpt
ions.ImagePlusText);
});
// Unbound column for deleting records.
col.Commands(cmd1 =>
{
cmd1.Command(CommandTypes.Delete).Text("Delete").ImageUrl("/Content/Del
ete.png").ItemType(UnBoundItemTypes.Button).ItemOption(UnboundItemOptio
ns.TextOnly);
});
col.Commands(command =>
{
command.Command(CommandTypes.Custom)
.ItemType(UnBoundItemTypes.Button)
.ItemOption(UnboundItemOptions.TextOnly)
.Mapper("ViewDetails?Orderid=${OrderID}")
.Text("View");
});
}).UnBound(true); // Unbound must be true
to make it as unbound column
})
Note: The Mapper action Command in can be used in unbound columns for command
type as Custom only. If we define the mapper for defined commands like Edit, Save,
Cancel, and Insert there will be an unnecessary conflict between the grid mappers for
editing actions and mapper defined for commands. To avoid this type of conflicts we
suggest you to use the Unbound Mapper action for Custom command only.
7. Specify the primary property which uniquely identifies the grid record.
View[ASPX]
<%=Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Editing( edit=>{
View[cshtml]
@{ Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Editing( edit=>{
8. In the controller, create a method to add new records to the grid as displayed below. In this
example, the repository method Add() is being created to insert records to the database.
Refer the repository action method displayed below.
Controller
/// <summary>
/// Used to insert the record into the database and refresh the grid.
/// </summary>
/// <param name="ord">Editable order.</param>
/// <returns>HtmlActionResult returns the data displayed in the
grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddOrder(EditableOrder ord)
{
// Repository action method Add() is used to insert records in the data
source.
OrderRepository.Add(ord);
// After adding the record into the database, refresh the grid.
var data = OrderRepository.GetAllRecords();
return data.GridJSONActions<EditableOrder>();
}
In this example, the repository method Update() is used to update records to the data source.
Controller
/// Used to insert the record into database and refresh the grid.
/// </summary>
10. In the controller, create a method to delete the records from the database as displayed
below.
In this example, the repository action Delete() will delete the record from the data source.
Controller
/// <summary>
/// Used to delete the records from the data source and refresh the
grid.
/// </summary>
/// <param name="OrderID">Primary key values.</param>
/// <returns>HtmlActionResult returns the data displayed in the
grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult DeleteOrder(int OrderID)
{
// Repository action Delete() deletes the given primary value record
from the data source.
OrderRepository.Delete(OrderID);
// After deleting, refresh the grid.
var data = OrderRepository.GetAllRecords();
return data.GridJSONActions<EditableOrder>();
}
11. In the controller, create a method to View the records from the database as displayed
below.
In this example, the repository action ViewDetails() will show the record from the data source.
Controller
{
var data = OrderRepository.GetAllRecords().Where(ord =>
ord.OrderID == Orderid).FirstOrDefault();
return Json(new { OrderDetails = data },
JsonRequestBehavior.AllowGet);
}
12. Run the application and click the Edit button to edit the record. The grid will appear as
displayed below.
View[ASPX]
<head runat="server">
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server"
/></title>
………
<script src="<%=
Url.Content("~/Scripts/MicrosoftMvcValidation.debug.js") %>"
type="text/javascript"></script>
</head>
[_Layout.cshtml]
<head runat="server">
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server"
/></title>
………
<script
src="@Url.Content("~/Scripts/MicrosoftMvcValidation.debug.js ")"
type="text/javascript"></script>
</head>
61.
Note: Add the following script files when the UnobtrusiveJavaScriptEnabled is true in the
web.config file.
[Web.config]
<configuration>
<appSettings>
<add key='UnobtrusiveJavaScriptEnabled' value='true'/>
</appSettings>
[_Layout.cshtml]
<head>
. . . .
. . . .
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")"
type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")"
type="text/javascript"></script>
<script
src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"
type="text/javascript"></script>
</head>
[Site.Master]
<head runat="server">
. . . .
. . . .
<script src="<%=Url.Content("~/Scripts/jquery.unobtrusive-
ajax.min.js")%>" type="text/javascript"></script>
<script src="<%=Url.Content("~/Scripts/jquery.validate.min.js")%>"
type="text/javascript"></script>
<script
src="<%=Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")%
>" type="text/javascript"></script>
</head>
View[ASPX]
<%= Html.Syncfusion().Grid<EditableOrder>("Grid1",
(GridPropertiesModel<EditableOrder>)ViewData["GridModel"])
})%>
View[cshtml]
@( Html.Syncfusion().Grid<EditableOrder>("Grid1",
(GridPropertiesModel<EditableOrder>)ViewData["GridModel"]))
[Controller]
GridCommands<EditableOrder> cmd1 = new GridCommands<EditableOrder>()
{
ItemType = UnBoundItemTypes.Button,
ImageUrl = Url.Content("~/Content/Images/Edit.png"),
ItemOption = UnboundItemOptions.ImageOnly,
Text = "Edit",
Type = "Edit"
};
GridCommands<EditableOrder> cmd2 = new
GridCommands<EditableOrder>()
{
ItemType = UnBoundItemTypes.HyperLink,
ImageUrl = Url.Content("~/Content/Images/Update.png"),
ItemOption = UnboundItemOptions.ImagePlusText,
Text = "Update",
Type = "Update"
};
GridCommands<EditableOrder> cmd3 = new
GridCommands<EditableOrder>()
{
ItemType = UnBoundItemTypes.Button,
ImageUrl = Url.Content("~/Content/Images/Delete.png"),
ItemOption = UnboundItemOptions.TextOnly,
Text = "Delete",
Type = "Delete"
};
GridCommands<EditableOrder> cmd4 = new
GridCommands<EditableOrder>()
{
ItemType = UnBoundItemTypes.Button,
ImageUrl = Url.Content("~/Content/Images/Delete.png"),
ItemOption = UnboundItemOptions.TextOnly,
Text = "View",
Type = "Custom",
Mapper = "ViewDetails?Orderid={OrderID}"
};
List<GridCommands<EditableOrder>> commandColl = new
List<GridCommands<EditableOrder>>();
commandColl.Add(cmd1);
commandColl.Add(cmd2);
commandColl.Add(cmd3);
commandColl.Add(cmd4);
Note: We can use Mapper action Command in unbound column for command type as Custom
only. If we define the mapper for defined commands like Edit, Save, Cancel, Insert there will be
unnecessary conflict between the grid mappers for editing actions and mapper defined for
commands. To avoid this type of conflicts we suggest you to use the Unbound Mapper action for
Custom command only.
5. Create a GridPropertiesModel in the Index method and assign the grid properties in the
model.
Controller
AllowPaging = true,
AllowSorting = true,
AllowGrouping=true,
AutoFormat=Skins.Marble
};
model.Columns = new List<GridColumn<EditableOrder>>
{
new GridColumn<EditableOrder>
{
ColumnType=typeof(DateTime?)
},
new GridColumn<EditableOrder>
{
HeaderText = "Freight",
MappingName = "Freight",
ColumnType=typeof(decimal)
},
new GridColumn<EditableOrder>
{
IsUnbound = true,
MappingName = "Manage Records",
ColumnType=typeof(string),
Commands = commandColl
}
};
ViewData["GridModel"] = model;
6. Enable editing by using the Editing property in the GridPropertiesModel and configure the
editing properties such as AddNew, AllowEdit, and AllowDelete as displayed below.
Controller
// Create an object for grid editing and enable the edit, add
new, and delete actions.
GridEditing edit = new GridEditing() { AllowEdit = true, AllowDelete =
true };
// Set the action mappers for the insert, delete, and save actions.
edit.DeleteMapper = "DeleteOrder";
edit.GridSaveMapper = "OrderSave";
edit.InsertAction = "AddOrder";
Controller
8. Specify the primary property which uniquely identifies the grid record.
Controller
Controller
10. In the controller, create a method to add new records to the grid as displayed below. In this
example, the repository method Add() is being created to insert records to the database.
Refer to the repository action method displayed below.
Controller
/// <summary>
/// Used to insert the record into the database and refresh the grid.
/// </summary>
/// <param name="ord">Editable order.</param>
/// <returns>HtmlActionResult returns the data displayed in the
grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddOrder(EditableOrder ord)
{
// Repository action method Add() is used to insert records in the data
source.
OrderRepository.Add(ord);
// After adding the record into the database, refresh the grid.
var data = OrderRepository.GetAllRecords();
return data.GridJSONActions<EditableOrder>();
}
In this example, the repository method Update() is used to update records to the data source:
Controller
/// Used to insert the record in the database and refresh the grid.
/// </summary>
/// <param name="ord">Editable order.</param>
/// <returns>HtmlActionResult returns the data displayed in the
grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult OrderSave(EditableOrder ord)
{
// Repository action method Update is used to update the records into
datasource.
OrderRepository.Update(ord);
//After saving the records into datasource refresh the grid.
var data = OrderRepository.GetAllRecords();
return data.GridJSONActions<EditableOrder>();
}
12. In the controller, create a method to delete the records from the database as displayed
below.
In this example, the repository action Delete() will delete the record from the data source.
Controller
/// <summary>
/// Used to delete records from the data source and refresh the grid.
/// </summary>
/// <param name="OrderID">Primary key values.</param>
/// <returns>HtmlActionResult returns the data displayed in the
grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult DeleteOrder(int OrderID)
{
// Repoistory action Delete() deletes the given primary value record
from the data source.
OrderRepository.Delete(OrderID);
// After deleting, refresh the grid.
var data = OrderRepository.GetAllRecords();
return data.GridJSONActions<EditableOrder>();
}
13. In the controller, create a method to View the records from the database as displayed
below.
In this example, the repository action ViewDetails() will show the record from the data source.
Controller
{
var data = OrderRepository.GetAllRecords().Where(ord =>
ord.OrderID == Orderid).FirstOrDefault();
return Json(new { OrderDetails = data },
JsonRequestBehavior.AllowGet);
}
14. Run the application. The grid will appear as displayed below.
if (orders == null)
{
HttpContext.Current.Session["Orders"] = orders = (from
/// <summary>
/// Used for add the new Editable order to datasource.
/// </summary>
/// <param name="order">EditableOrder</param>
public static void Add(EditableOrder order)
{
GetAllRecords().Insert(0, order);
}
/// <summary>
/// Used to find the order from the datasource.
/// </summary>
/// <param name="OrderID">OrderID</param>
/// <returns>EditableOrder as result</returns>
public static EditableOrder Select(int? OrderID)
{
return result;
}
/// <summary>
/// Used to delete the EditableOrder from datasource using
OrderID.
/// </summary>
/// <param name="OrderID">OrderID</param>
public static void Delete(int OrderID)
{
EditableOrder result = GetAllRecords().Where(o => o.OrderID
== OrderID).FirstOrDefault();
GetAllRecords().Remove(result);
}
/// <summary>
/// Used to update the changes to datasource.
/// </summary>
/// <param name="order"></param>
public static void Update(EditableOrder order)
{
EditableOrder result = GetAllRecords().Where(o => o.OrderID
== order.OrderID).FirstOrDefault();
if (result != null)
{
result.OrderID = order.OrderID;
result.CustomerID = order.CustomerID;
result.EmployeeID = order.EmployeeID;
result.OrderDate = order.OrderDate;
result.ShipAddress = order.ShipAddress;
result.ShipCity = order.ShipCity;
result.ShipCountry = order.ShipCountry;
result.ShipName = order.ShipName;
result.ShipRegion = order.ShipRegion;
result.ShipPostalCode = order.ShipPostalCode;
result.Freight = order.Freight;
}
}
}
namespace MvcSampleApplication.Models
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
/// <summary>
/// JSON mode order class.
/// </summary>
public class JSONOrder
{
public int OrderID
{
get;
set;
}
48393, 123456789));
return result;
}
}
/// <summary>
/// OrderDetailEdit Model.
/// </summary>
public partial class OrderDetailEdit
{
[Required(ErrorMessage = "Order ID is required.")]
public int OrderID
{
get;
set;
}
[Required(ErrorMessage = "Product ID is required.")]
public int ProductID
{
get;
set;
}
[Required(ErrorMessage = "Quantity is required.")]
public Int16 Quantity
{
get;
set;
}
public Decimal UnitPrice
{
get;
set;
}
public Single Discount
{
get;
set;
}
}
4.7.9.7 OrderDetailRepository
public static class OrderDetailRepository
{
public static IList<OrderDetailEdit> GetAllRecords(int? OrderID
)
{
IList<OrderDetailEdit> ordersdetails;
ordersdetails = (IList<OrderDetailEdit>)HttpContext.Current
.Session["childgridGlobal"];
if (ordersdetails == null)
{
HttpContext.Current.Session["childgridGlobal"] = orders
details = (from ord in new NorthwindDataContext().Order_Details//.Take(
200)
select new OrderDetailE
dit
{
OrderID = ord.Order
ID,
ProductID = ord.Pro
ductID,
UnitPrice = ord.Uni
tPrice,
Quantity = ord.Quan
tity,
Discount = ord.Disc
ount
}).ToList();
}
if(OrderID != null)
ordersdetails = ordersdetails.Where(o => o.OrderID == O
rderID).ToList();
return ordersdetails;
}
public static void Delete(int? Orderid, int Productid)
{
OrderDetailEdit result = GetAllRecords(Orderid).Where(o =>
o.ProductID == Productid).FirstOrDefault();
GetAllRecords(Orderid).Remove(result);
}
public static OrderDetailEdit Select(int? OrderID)
{
return result;
}
public static void Update(OrderDetailEdit order)
{
OrderDetailEdit result = GetAllRecords(order.OrderID).Where
(o => o.ProductID == order.ProductID).FirstOrDefault();
if (result != null)
{
result.OrderID = order.OrderID;
result.ProductID = order.ProductID;
result.UnitPrice = order.UnitPrice;
result.Quantity = order.Quantity;
result.Discount = order.Discount;
}
}
}
4.8 Exporting
4.8.1 Excel Export
Export to Excel is one of the most common functionalities that is required in .NET. The Essential
Grid Control has in-built support for Excel Export. You can download data from the Grid control to
an Excel spreadsheet for offline verification and/or computation. This can be achieved by using
the GridExcelExportActionResult<T> extension. This extension applies the Grid control's styles
and formats to Excel. The GridExcelExportActionResult<T> is derived from
GridActionResultBase<T>. The XlsIO libraries are used to support the conversion of the Grid
contents to Excel.
All the content from a Grid can be converted to an Excel Spreadsheet. It also provides the option
to specify the version of the Excel file by using the ExcelVersion enum. The versions that can be
specified are as follows:
ExcelVersion.Excel97to2003
ExcelVersion.Excel2007
ExcelVersion.Excel2010
Properties
return
data.GridExportToExcel<Order>("
GridExcel.xlsx",
ExcelVersion.Excel2007);
xcel2010 GridExcel.xlsx",
ExcelVersion.Excel2007);
Methods
The steps to enable the Excel exporting feature through GridBuilder are as follows:
1. Create a model in the application. Refer to How to>Adding a Model to the Application.
2. Create a strongly typed view. Refer to How to>Strongly Typed View.
3. In the view, use the Model property in the Datasource(), to bind the data source.
62.
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("OrdersGrid")
.Datasource(Model)
.Caption("Orders")
.Column(column =>
{
column.Add(c => c.OrderID).HeaderText("Order
ID");
column.Add(c => c.OrderDate).HeaderText("Order
63.
View [cshtml]
@{ Html.Syncfusion().Grid<Order>("OrdersGrid")
.Datasource(Model)
.Caption("Orders")
.Column(column =>
{
column.Add(c => c.OrderID).HeaderText("Order
ID");
column.Add(c => c.OrderDate).HeaderText("Order
Date").Format("{0:dddd, MMMM d, yyyy}");
column.Add(c =>
c.CustomerID).HeaderText("Customer ID");
column.Add(c => c.ShipCountry).HeaderText("Ship
Country");
column.Add(c => c.ShipCity).HeaderText("Ship
City");
column.Add(c =>
c.ShipPostalCode).HeaderText("Ship postal Code");
column.Add(c =>
c.Freight).HeaderText("Frieght").Format("{Freight:#,#}");
})
.EnablePaging()
.EnableSorting()
.AutoFormat(Skins.Sandune)
.Render();
}
64.
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("OrdersGrid")
.Datasource(Model)
.Caption("Orders")
.ToolBar(tools =>
tools.Export(GridToolBarItems.ExcelExport, "Export",
"ExportToExcel"))
%>
65.
View [cshtml]
@{ Html.Syncfusion().Grid<Order>("OrdersGrid")
.Datasource(Model)
.Caption("Orders")
.ToolBar(tools =>
tools.Export(GridToolBarItems.ExcelExport, "Export",
"ExportToExcel")).Render();
}
5. Specify the file name and Excel version details in the ExportToExcel() method.
Controller
/// <summary>
/// Used to export the grid as an Excel file.
/// </summary>
/// <param name="grid">Grid object.</param>
/// <returns>Excel file.</returns>
public ActionResult ExportToExcel()
{
var data = new
NorthwindDataContext().Orders.Take(200).ToList();
return data.GridExportToExcel<Order>("GridExcel.xlsx",
ExcelVersion.Excel2007);
}
6. Run the application and click the Export button. The grid will appear as displayed
below.
1. Create a model in the application. Refer to How to>Adding a Model to the Application.
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. Add the following code in the Index.aspx file to create the Grid control in the view.
66.
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("Orders_Grid","GridModel", column=> {
column.Add(c => c.OrderID).HeaderText("Order
ID");
column.Add(c => c.OrderDate).HeaderText("Order
Date").Format("{0:dddd, MMMM d, yyyy}");
column.Add(c =>
c.CustomerID).HeaderText("Customer ID");
column.Add(c => c.ShipCountry).HeaderText("Ship
Country");
column.Add(c => c.ShipCity).HeaderText("Ship
City");
column.Add(c =>
c.ShipPostalCode).HeaderText("Ship postal Code");
column.Add(c =>
c.Freight).HeaderText("Frieght").Format("{Freight:#,#}");
})%>
View [cshtml]
@( Html.Syncfusion().Grid<Order>("Orders_Grid","GridModel", column=> {
column.Add(c => c.OrderID).HeaderText("Order
ID");
column.Add(c => c.OrderDate).HeaderText("Order
Date").Format("{0:dddd, MMMM d, yyyy}");
column.Add(c =>
c.CustomerID).HeaderText("Customer ID");
column.Add(c => c.ShipCountry).HeaderText("Ship
Country");
column.Add(c => c.ShipCity).HeaderText("Ship
City");
column.Add(c =>
c.ShipPostalCode).HeaderText("Ship postal Code");
column.Add(c =>
c.Freight).HeaderText("Frieght").Format("{Freight:#,#}");
}))
4. Create a GridPropertiesModel in the Index method and the assign grid properties in
the model.
Controller
Note: The syntax for the ExcelExport item is toolbarcaption + ~ +mapperName. In this example,
Export is the caption and ExcelToExcel is the name of the mapper.
ViewData["GridModel"] = model;
7. Specify the file name and the Excel version details in the ExportToExcel() method.
Controller
/// <summary>
/// Used to export the grid as an Excel worksheet.
/// </summary>
/// <param name="grid">Grid object.</param>
/// <returns>Excel file.</returns>
public ActionResult ExportToExcel()
{
var data = new
NorthwindDataContext().Orders.Take(200).ToList();
return data.GridExportToExcel<Order>("GridExcel.xlsx",
ExcelVersion.Excel2007);
}
8. Run the application and click the Export button. The grid will appear as displayed
below.
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("OrdersGrid")
.Datasource(Model)
.Caption("Orders")
.Column(column =>
{
column.Add(c => c.OrderID).HeaderText("Order
ID");
column.Add(c => c.OrderDate).HeaderText("Order
Date").Format("{0:dddd, MMMM d, yyyy}");
column.Add(c =>
c.CustomerID).HeaderText("Customer ID");
column.Add(c =>
c.ShipCountry).HeaderText("Ship Country");
column.Add(c => c.ShipCity).HeaderText("Ship
City");
column.Add(c =>
c.ShipPostalCode).HeaderText("Ship postal Code");
column.Add(c =>
c.Freight).HeaderText("Frieght").Format("{Freight:#,#}");
})
.EnablePaging()
.EnableSorting()
.AutoFormat(Skins.Sandune)
%>
View [cshtml]
@{ Html.Syncfusion().Grid<Order>("OrdersGrid")
.Datasource(Model)
.Caption("Orders")
.Column(column =>
{
column.Add(c => c.OrderID).HeaderText("Order
ID");
column.Add(c => c.OrderDate).HeaderText("Order
Date").Format("{0:dddd, MMMM d, yyyy}");
column.Add(c =>
c.CustomerID).HeaderText("Customer ID");
column.Add(c =>
c.ShipCountry).HeaderText("Ship Country");
column.Add(c => c.ShipCity).HeaderText("Ship
City");
column.Add(c =>
c.ShipPostalCode).HeaderText("Ship postal Code");
column.Add(c =>
c.Freight).HeaderText("Frieght").Format("{Freight:#,#}");
})
.EnablePaging()
.EnableSorting()
.AutoFormat(Skins.Sandune)
.Render();
}
4. Create a button element in the view page and write the code displayed below for the
button click event.
69.
<script type="text/javascript">
$(document).ready(function () {
$("#export").bind('click', function () {
// Find the gridobject;
var gridObj = $find("OrdersGrid");
// Set the ExcelExport action mapper using
Set_ExcelExportMapper().
gridObj.set_ExcelExportMapper("ExportToExcel");
</script>
5. Specify the file name and Excel version details in the ExportToExcel() method.
Controller
/// <summary>
/// Used to export the grid as an Excel worksheet.
/// </summary>
/// <param name="grid">Grid object.</param>
/// <returns>Excel file.</returns>
public ActionResult ExportToExcel()
{
var data = new
NorthwindDataContext().Orders.Take(200).ToList();
return data.GridExportToExcel<Order>("GridExcel.xlsx",
ExcelVersion.Excel2007);
}
6. Run the application and click the Export button. The grid will appear as displayed
below.
View[ASPX]
<%=Html.Syncfusion().Grid<Order>("OrdersGrid")
.Datasource(Model)
.Caption("Orders")
---------------
---------------
.ToolBar( toolbar =>
{
toolbar.Add(GridToolBarItems.PDFExport,"PDF
Export");
})
.Mappers(map =>
{
map.ExportPdfAction("ExportToPDF");
})
%>
View[cshtml]
@ { Html.Syncfusion().Grid<Order>("OrdersGrid")
.Datasource(Model)
.Caption("Orders")
---------------
---------------
.ToolBar( toolbar =>
{
toolbar.Add(GridToolBarItems.PDFExport,"PDF
Export");
})
.Mappers(map =>
{
map.ExportPdfAction("ExportToPDF");
}).Render();
}
6. Specify the file name, PDF version, and export option details in the GridExportToPDF()
method.
Controller
City");
column.Add(c => c.ShipPostalCode).HeaderText("Ship
postal Code");
column.Add(c =>
c.Freight).HeaderText("Frieght").Format("{Freight:#,#}");
});
%>
View[cshtml]
Controller
6. Specify the file name, PDF version, export option details in the GridExportToPDF()
method.
Controller
public ActionResult ExportToPDF(PagingParams args)
{
var data = new
NorthwindDataContext().Orders.Take(200).ToList();
return data.GridExportToPDF<Order>("GridPDF.pdf",
PdfVersion.Version1_7, args.ExportOption);
}
Sample Link
To view the samples, follow the steps below:
1. Open the Grid sample browser from the dashboard (Refer to the Samples and Location
chapter).
2. Navigate to Grid.MVC > Exporting > Export
This feature allows you to export normal and nested grids to Word formats, as you can see in the
screenshots below:
Using this feature, you can export the grid to Word and PDF formats, and can format the cells of
the exported grid.
This feature supports the export of both normal and nested (hierarchical) grids as well.
View[ASPX]
<%=Html.Syncfusion().Grid<Order>("OrdersGrid")
.Datasource(Model)
.Caption("Orders")
----------------
----------------
.ToolBar( toolbar =>
{
toolbar.Add(GridToolBarItems.WordExport,"Word
Export");
})
.Mappers(map =>
{
map. ExportWordAction("ExportToWord");
})
%>
View[cshtml]
@ { Html.Syncfusion().Grid<Order>("OrdersGrid")
.Datasource(Model)
.Caption("Orders")
----------------
----------------
.ToolBar( toolbar =>
{
toolbar.Add(GridToolBarItems.WordExport,"Word
Export");
})
.Mappers(map =>
{
map. ExportWordAction("ExportToWord");
}).Render();
}
6. Specify the file name and document version details in the GridExportToWord() method.
Controller
public ActionResult ExportToWord(PagingParams args)
{
var data = new
NorthwindDataContext().Orders.Take(200).ToList();
return data.GridExportToWord<Order>("GridWord.doc",
DocumentVersion.Word2007, args.ExportOption);
}
72.
View[cshtml]
View[cshtml]
AllowSorting = true
};
6. Specify the file name, PDF version, and export option details in the GridExportToWord()
method.
Controller
4.8.4 Properties
Exporting Grid to PDF and Word are two different actions that require slightly different properties,
methods, and events.
Properties to be used for PDF Export
Type of
Property Description Value it accepts Dependencies
property
Type of
Property Description Value it accepts Dependencies
property
Returns the
name of the
FileName String Any type of String NA
exported PDF
file
PdfVersion.Version1_1
PdfVersion.Version1_2
PdfVersion.Version1_3
Gets or sets
PdfVersion the version of PdfVersion.Version1_4
PdfVersion NA
the PDF PdfVersion.Version1_5
Document
PdfVersion.Version1_6
PdfVersion.Version1_7
All
Returns the
ConverterOptionsExt exporting Enum Visible NA
options
Specifies
whether True
ExportNestedTables nested tables bool NA
can be False
exported
Specifies
whether you True
UseAutoFormat can use the in- bool NA
built styles for False
Grid
Dependenci
Property Description Type of property Value it accepts
es
DocumentVersion.Word2000
DocumentVersion.Word2002
WordVersion Gets or sets the version
DocumentVersion DocumentVersion.Word2003 NA
of the Word Document
DocumentVersion.Word2007
All
ConverterOptions Returns the exporting
Enum Visible NA
Ext options
4.8.5 Methods
The methods used for both Grid to PDF and Word export are tabulated in the following sections:
For PDF Export
4.8.6 Events
For PDF Export
IWTextRange
4.8.7 How to Format Cells and Rows in a Grid that Was Exported
to PDF
You can use C# or VB code as shown below to format cells and rows in an exported grid.
View[ASPX]
<%=Html.Syncfusion().Grid<Order>("OrdersGrid")
.Datasource(Model)
.Caption("Orders")
-------------
-------------
.ToolBar( toolbar =>
{
toolbar.Add(GridToolBarItems.PDFExport,"PDF
Export");
})
.Mappers(map =>
{
map.ExportPdfAction("ExportToPDF");
})
%>
View[cshtml]
@ { Html.Syncfusion().Grid<Order>("OrdersGrid")
.Datasource(Model)
.Caption("Orders")
-------------
-------------
.ToolBar( toolbar =>
{
toolbar.Add(GridToolBarItems.PDFExport,"PDF
Export");
})
.Mappers(map =>
{
map.ExportPdfAction("ExportToPDF");
})
}
Controller
QueryExportPdfRowInfo
QueryExportPdfCellInfo
View[ASPX]
<%=Html.Syncfusion().Grid<Order>("OrdersGrid","GridModel", column =>
{
column.Add(c => c.OrderID).HeaderText("Order ID");
column.Add(c => c.OrderDate).HeaderText("Order
Date").Format("{0:dddd, MMMM d, yyyy}");
column.Add(c => c.CustomerID).HeaderText("Customer
ID");
column.Add(c => c.ShipCountry).HeaderText("Ship
Country");
column.Add(c => c.ShipCity).HeaderText("Ship
City");
column.Add(c => c.ShipPostalCode).HeaderText("Ship
postal Code");
column.Add(c =>
c.Freight).HeaderText("Frieght").Format("{Freight:#,#}");
});
%>
View[cshtml]
@ { Html.Syncfusion().Grid<Order>("OrdersGrid","GridModel", column =>
{
column.Add(c => c.OrderID).HeaderText("Order ID");
column.Add(c => c.OrderDate).HeaderText("Order
Date").Format("{0:dddd, MMMM d, yyyy}");
column.Add(c => c.CustomerID).HeaderText("Customer
ID");
column.Add(c => c.ShipCountry).HeaderText("Ship
Country");
column.Add(c => c.ShipCity).HeaderText("Ship
City");
column.Add(c => c.ShipPostalCode).HeaderText("Ship
postal Code");
column.Add(c =>
c.Freight).HeaderText("Frieght").Format("{Freight:#,#}");
});
}
Controller
Controller
ToolbarSettings toolbar = new ToolbarSettings ();
toolbar.Enable = true; // Used to enable the toolbar.
// Add the PDF toolbar item in toolbar with caption and mapper name.
toolbar.Items.Add(new ToolbarOptions() { ItemType=
GridToolBarItems.ExcelExport, Mapper = "ExportToPDF"});
model.ToolBar = toolbar;
Controller
QueryExportPdfRowInfo
QueryExportPdfCellInfo
View[ASPX]
<%=Html.Syncfusion().Grid<Order>("OrdersGrid")
.Datasource(Model)
.Caption("Orders")
----------
----------
.ToolBar( toolbar =>
{
toolbar.Add(GridToolBarItems.WordExport,"Word
Export");
})
.Mappers(map =>
{
map. ExportWordAction("ExportToWord");
})
%>
View[cshtml]
@ { Html.Syncfusion().Grid<Order>("OrdersGrid")
.Datasource(Model)
.Caption("Orders")
----------
----------
.ToolBar( toolbar =>
{
toolbar.Add(GridToolBarItems.WordExport,"Word
Export");
})
.Mappers(map =>
{
map. ExportWordAction("ExportToWord");
})
}
Controller
QueryExportWordCellInfo
{
textRange.CharacterFormat.FontSize = Office2007Blue.FontName;
}
}
QueryExportWordRowInfo
c.Freight).HeaderText("Frieght").Format("{Freight:#,#}");
});
%>
View[cshtml]
@ { Html.Syncfusion().Grid<Order>("OrdersGrid","GridModel", column =>
{
column.Add(c => c.OrderID).HeaderText("Order ID");
column.Add(c => c.OrderDate).HeaderText("Order
Date").Format("{0:dddd, MMMM d, yyyy}");
column.Add(c => c.CustomerID).HeaderText("Customer
ID");
column.Add(c => c.ShipCountry).HeaderText("Ship
Country");
column.Add(c => c.ShipCity).HeaderText("Ship
City");
column.Add(c => c.ShipPostalCode).HeaderText("Ship
postal Code");
column.Add(c =>
c.Freight).HeaderText("Frieght").Format("{Freight:#,#}");
});
}
77. Create a GridPropertiesModel and assign the grid properties in the model.
Controller
78. Configure the GridPropertiesModel as displayed below to accept the WordExport and
ActionMapper and to render the toolbar.
Controller
// Add the PDF toolbar item to the toolbar with a caption and mapper
name.
toolbar.Items.Add(new ToolbarOptions() { ItemType=
GridToolBarItems.ExcelExport, Mapper = "ExportToWord"});
model.ToolBar = toolbar;
Controller
QueryExportWordCellInfo
QueryExportWordRowInfo
4.9 Formatting
Essential Grid allows you to format grid cells. You can achieve this formatting by three methods.
They are:
Using column formatting
Using custom actions
Using conditional formatting
Properties
CssClass Used to CssClass for the the String Any class name
Column. in string format
Methods
dynamically.
Executed for
every cell in
the grid.
Grid uses Format() method for formatting the column. This Format() method format both bound
columns and unbounds column data. In bound columns, it formats only the column values where
as unbound columns it formats the column by records.
Bound Columns
1. Create a model in the application (Refer to How to>Creating the Generic Collection
Model and How to>AutoFormattingClass).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. In the view, you can use its Model property in Datasource() to bind the data source.
80.
View [ASPX]
<%=Html.Syncfusion().Grid<AutoFormatting>("FormatGrid")
.Datasource(Model)
.ShowCaption(false)
.ShowRowHeader(false)
.AutoFormat(Skins.Sandune)
%>
81.
View [cshtml]
@{ Html.Syncfusion().Grid<AutoFormatting>("FormatGrid")
.Datasource(Model)
.ShowCaption(false)
.ShowRowHeader(false)
.AutoFormat(Skins.Sandune)
.Render();
}
<%=Html.Syncfusion().Grid<AutoFormatting>("FormatGrid")
.Datasource(Model)
.ShowCaption(false)
.ShowRowHeader(false)
.AutoFormat(Skins.Sandune)
.Column( column =>
{
column.Add(c =>
c.Currency).HeaderText("Currency").Format("{0:$###,###.##}"
);
column.Add(c =>
c.Dates).HeaderText("Dates").Format("{0:MM/dd/yyyy
hh:mm:ss}");
column.Add(c =>
c.Number).HeaderText("Number").Format("{0:# inch}");
column.Add(c =>
c.Telephone).HeaderText("Telephone").Format("{0:1 - (###)
###-####}");
})
%>
83.
View [cshtml]
@{ Html.Syncfusion().Grid<AutoFormatting>("FormatGrid")
.Datasource(Model)
.ShowCaption(false)
.ShowRowHeader(false)
.AutoFormat(Skins.Sandune)
.Column( column =>
{
column.Add(c =>
c.Currency).HeaderText("Currency").Format("{0:$###,###.##}"
);
column.Add(c =>
c.Dates).HeaderText("Dates").Format("{0:MM/dd/yyyy
hh:mm:ss}");
column.Add(c =>
c.Number).HeaderText("Number").Format("{0:# inch}");
column.Add(c =>
c.Telephone).HeaderText("Telephone").Format("{0:1 - (###)
###-####}");
}).Render();
}
5. Run the sample. The grid will look like the following screenshot.
UnboundColumn
Refer to more information regarding the formatting of unbound columns in Data
Binding>Unbound Columns.
Sample Link
To view the samples, follow the steps below:
1. Open the Grid sample browser from the dashboard (Refer to the Samples and Location
chapter).
Navigate to Grid.MVC > Formatting > Column Formatting
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("OrdersGrid")
.Datasource(Model)
.Caption("Orders")
.EnablePaging()
.EnableSorting()
.AutoFormat(Skins.Sandune)
.Column(column =>
{
column.Add(c =>
c.OrderID).HeaderText("Order ID");
column.Add(c =>
c.OrderDate).HeaderText("Order
Date").Format("{OrderDate:dd/MM/yyyy}");
column.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
column.Add(c =>
c.CustomerID).HeaderText("Customer ID");
column.Add(c =>
c.ShipCountry).HeaderText("Ship Country");
column.Add(c =>
c.ShipCity).HeaderText("Ship City");
})
%>
View [cshtml]
@{ Html.Syncfusion().Grid<Order>("OrdersGrid")
.Datasource(Model)
.Caption("Orders")
.EnablePaging()
.EnableSorting()
.AutoFormat(Skins.Sandune)
.Column(column =>
{
column.Add(c =>
c.OrderID).HeaderText("Order ID");
column.Add(c =>
c.OrderDate).HeaderText("Order
Date").Format("{OrderDate:dd/MM/yyyy}");
column.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
column.Add(c =>
c.CustomerID).HeaderText("Customer ID");
column.Add(c =>
c.ShipCountry).HeaderText("Ship Country");
column.Add(c =>
c.ShipCity).HeaderText("Ship City");
}).Render(); }
[CSS]
<style type="text/css">
.CustomCss
{
text-align:right;
background-color:Aqua;
}
</style>
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("OrdersGrid")
.Datasource(Model)
.Caption("Orders")
.EnablePaging()
.EnableSorting()
.AutoFormat(Skins.Sandune)
.Column(column =>
{
column.Add(c => c.OrderID).HeaderText("Order
ID");
column.Add(c => c.OrderDate).HeaderText("Order
Date").Format("{OrderDate:dd/MM/yyyy}");
column.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
column.Add(c =>
c.CustomerID).HeaderText("Customer ID");
column.Add(c => c.ShipCountry).HeaderText("Ship
Country").CssClass("CustomCss");
column.Add(c => c.ShipCity).HeaderText("Ship
City");
})
%>
View [cshtml]
@{ Html.Syncfusion().Grid<Order>("OrdersGrid")
.Datasource(Model)
.Caption("Orders")
.EnablePaging()
.EnableSorting()
.AutoFormat(Skins.Sandune)
.Column(column =>
{
column.Add(c => c.OrderID).HeaderText("Order
ID");
column.Add(c => c.OrderDate).HeaderText("Order
Date").Format("{OrderDate:dd/MM/yyyy}");
column.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
column.Add(c =>
c.CustomerID).HeaderText("Customer ID");
column.Add(c => c.ShipCountry).HeaderText("Ship
Country").CssClass("CustomCss");
column.Add(c => c.ShipCity).HeaderText("Ship
City");
}).Render();
}
Properties
GridTableCellType
.IndentCell
GridTableCellType
.TopLeftHeaderCel
l
GridTableCellType
.RowHeaderCell
GridTableCellType
.ColumnHeaderCel
GridTableCellType
.RecordPlusMinus
Cell
GridTableCellType
.RecordFieldCell
GridTableCellType
.AlternateRecordFi
eldCell
GridTableCellType
.AlternateRecordR
owHeaderCell
GridTableCellType
.EmptyCell
GridTableCellType
.CaptionCell
1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. In the view, you can use its Model property in Datasource() to bind the data source.
84.
View [ASPX]
<%=Html.Syncfusion().Grid<Product>("CustomGrid")
.Datasource(Model)
.Caption("Products")
.ShowRowHeader(false)
.AutoFormat(Skins.Sandune)
.Column(column =>{
Name");
column.Add(c => c.SupplierID).HeaderText("Supplier
ID");
column.Add(c => c.UnitPrice).HeaderText("Unit
Price");
column.Add(c => c.UnitsInStock).HeaderText("Units In
Stock");
column.Add(c => c.UnitsOnOrder).HeaderText("Units On
Order");
column.Add(c => c.ReorderLevel).HeaderText("Reorder
Level");
})
%>
85.
86.
View [cshtml]
@{ Html.Syncfusion().Grid<Product>("CustomGrid")
.Datasource(Model)
.Caption("Products")
.ShowRowHeader(false)
.AutoFormat(Skins.Sandune)
.Column(column =>{
View [ASPX]
<%=Html.Syncfusion().Grid<Product>("CustomGrid")
.Datasource(Model)
.Caption("Products")
.EnablePaging()
.QueryCellInfo(cell => Html.RenderAction("QueryAction",
"Formatting", new { args = cell }))
%>
89.
View [cshtml]
@{ Html.Syncfusion().Grid<Product>("CustomGrid")
.Datasource(Model)
.Caption("Products")
.EnablePaging()
.QueryCellInfo(cell => Html.RenderAction("QueryAction",
"Formatting", new { args = cell })).Render();
}
5. Create an action for the QueryAction () action as shown below to perform custom
formatting at the cell level.
Controller
if (args.Column.MappingName == "UnitsInStock")
{
if (args.Data.UnitsInStock <= 30)
args.HtmlAttributes["style"] =
"color:#ac0c0c;text-align:right";
}
if (args.Column.MappingName == "ReorderLevel")
{
if (args.Data.UnitsInStock < 25)
args.HtmlAttributes["style"] =
"color:#ac0c0c;text-align:right";
}
}
}
90.
91.
6. Set its data source and render the view.
92.
Controller
/// <summary>
/// Used to bind the grid.
/// </summary>
/// <returns>View page; it displays the grid.</returns>
public ActionResult Index()
{
var data = new
NorthwindDataContext().Products.Take(20).ToList();
return View(data);
}
7. In order to work with paging actions, create a Post method for Index actions, bind the
data source to the grid and assign the QueryAction to the QueryCellInfo property and
pass the data as a Aciton result to the view as shown in the following code.
Controller
/// <summary>
/// Paging/sorting requests are mapped to this method. This
method invokes the HtmlActionResult
/// from the grid. Required response is generated.
/// </summary>
/// <param name="args">Contains paging properties.</param>
/// <returns>
/// HtmlActionResult returns the data displayed on the grid.
/// </returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new
NorthwindDataContext().Products.Take(20).ToList();
var engine = data.GridActions<Product>() as
GridHtmlActionResult<Product>;
engine.GridModel.QueryCellInfo = QueryAction;
return engine;
}
View [ASPX]
<%=Html.Syncfusion().Grid<Product>("Orders_Grid","GridModel",
column=> {
column.Add(c =>
c.ProductID).HeaderText("Product ID");
column.Add(c =>
c.ProductName).HeaderText("Product Name");
column.Add(c =>
c.SupplierID).HeaderText("Supplier ID");
column.Add(c =>
c.UnitPrice).HeaderText("Unit Price");
column.Add(c =>
c.UnitsInStock).HeaderText("Units In Stock");
column.Add(c =>
c.UnitsOnOrder).HeaderText("Units On Order");
column.Add(c =>
c.ReorderLevel).HeaderText("Reorder Level"); })%>
View [cshtml]
@( Html.Syncfusion().Grid<Product>("Orders_Grid","GridModel",
column=> {
column.Add(c =>
c.ProductID).HeaderText("Product ID");
column.Add(c =>
c.ProductName).HeaderText("Product Name");
column.Add(c =>
c.SupplierID).HeaderText("Supplier ID");
column.Add(c =>
c.UnitPrice).HeaderText("Unit Price");
column.Add(c =>
c.UnitsInStock).HeaderText("Units In Stock");
column.Add(c =>
c.UnitsOnOrder).HeaderText("Units On Order");
column.Add(c => c.ReorderLevel).HeaderText("Reorder
Level"); }))
4. Create a GridPropertiesModel in the Index method. Assign grid properties in this model
and pass the model from the controller to the view using the ViewData class as shown
below.
93.
Controller
[ChildActionOnly]
public void QueryAction(GridTableCell<Product> cell)
{
// TableCellType is validation. Check for Record field
cells.
if (cell.TableCellType == GridTableCellType.RecordFieldCell
|| cell.TableCellType == GridTableCellType.AlternateRecordFieldCell)
{
if (cell.Column.MappingName == "UnitsInStock")
{
if (cell.Column.MappingName == "ReorderLevel")
{
if (cell.Data.UnitsInStock < 25)
{
// Apply background color and font style for
the record field cell.
cell.HtmlAttributes["style"] =
"color:#ac0c0c;background-color:Bisque;";
}
}
6. Bind the action to GridPropertiesModel and pass the model to the view using the View
Data method as given below:
96.
Controller
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("Grid1")
.Caption("Orders")
.AutoFormat(Skins.Sandune)
.ActionMode(ActionMode.JSON)
.ClientSideEvents(events => {
events.QueryCellInfo("QueryCellInfoHandler");
})
%>
View [cshtml]
@{ Html.Syncfusion().Grid<Order>("Grid1")
.Caption("Orders")
.AutoFormat(Skins.Sandune)
.ActionMode(ActionMode.JSON)
.ClientSideEvents(events => {
events.QueryCellInfo("QueryCellInfoHandler");
}).Render();
Controller
public ActionResult Index()
{
return View();
}
7. In order to work with the JSON mode actions, create a Post method for Index actions
and bind the data source to the grid as given in the following code.
97.
Controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new NorthwindDataContext().Orders.ToList();
return data.GridJSONActions<Order>();
}
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("Grid1","GridModel", column
s => {
columns.Add(p => p.OrderID)
columns.Add(p => p.CustomerID)
columns.Add(p => p.EmployeeID);
columns.Add(P => P.ShipCountry);
columns.Add(p => p.OrderDate).Format("{0:dd-MM-yyyy}");
})%>
View [cshtml]
@( Html.Syncfusion().Grid<Order>("Grid1","GridModel", columns => {
columns.Add(p => p.OrderID)
columns.Add(p => p.CustomerID)
columns.Add(p => p.EmployeeID);
columns.Add(P => P.ShipCountry);
columns.Add(p => p.OrderDate).Format("{0:dd-MM-yyyy}");
}))
4. Create a GridPropertiesModel in the Index method. Use the ActionMode property to set
the JSON mode.
5. Set the QueryCellInfo handler name using the QueryCellInfo property.
[Controller]
public ActionResult Index()
{
ClientSideEvents eve = new ClientSideEvents();
eve.QueryCellInfo = "QueryCellInfoHandler";
};
ViewData["GridModel"] = gridModel;
return View();
}
98.
JavaScript
ActionMode.JSON
ActionMode.Server
Default value:
ActionMode.Server
Methods
ActionMode.Server
Default value:
ActionMode.Server
Grid formatting can be applied to different grid row elements dynamically at run time. This can be
achieved by RowDataBound action. It provides the Htmlattributes object for a cell on demand.
RowDataBound is raised every time a request is made to access the style information for a row.
You can do any type of row formatting with this event.
It accepts GridTableRow<T> as its parameter which can be used to customize the rows of the
Grid control.
The following table describes the GridTableRow<T> properties:
Properties
alternate.
1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. In the view, use the Model property in Datasource() to bind the data source.
View [ASPX]
<%=Html.Syncfusion().Grid<Product>("CustomGrid")
.Datasource(Model)
.Caption("Products")
.EnablePaging()
.Column(column =>{
101.
View [cshtml]
@{ Html.Syncfusion().Grid<Product>("CustomGrid")
.Datasource(Model)
.Caption("Products")
.EnablePaging()
.Column(column =>{
4. Configure the RowDataBound() action as given below to perform custom formatting at the
row level.
102.
View [ASPX]
<%=Html.Syncfusion().Grid<Product>("CustomGrid")
.Datasource(Model)
.Caption("Products")
.EnablePaging()
.RowDataBound(row => Html.RenderAction("RowAction",
"Formatting", new { args = row }))
%>
View [cshtml]
@{ Html.Syncfusion().Grid<Product>("CustomGrid")
.Datasource(Model)
.Caption("Products")
.EnablePaging()
.RowDataBound(row => Html.RenderAction("RowAction",
"Formatting", new { args = row })).Render();
}
5. Create an action for the RowDataBound() as shown below to perform custom formatting at
the cell level.
Controller
103.
104.
6. Set its data source and render the view.
105.
Controller
/// <summary>
/// Used to bind the grid.
/// </summary>
/// <returns>View page; it displays the grid.</returns>
public ActionResult Index()
{
var data = new
NorthwindDataContext().Products.Take(20).ToList();
return View(data);
}
7. In order to work with paging actions, create a Post method for Index actions, bind the data
source to the grid and assign the QueryAction to the QueryCellInfo property and pass the
data as a Aciton result to the view as shown in the following code.
Controller
/// <summary>
/// Paging/sorting requests are mapped to this method. This
method invokes the HtmlActionResult
/// from the grid. Required response is generated.
/// </summary>
/// <param name="args">Contains paging properties.</param>
/// <returns>
/// HtmlActionResult returns the data displayed on the grid.
/// </returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new
NorthwindDataContext().Products.Take(20).ToList();
var engine = data.GridActions<Product>() as
GridHtmlActionResult<Product>;
engine.GridModel.RowDataBound = RowAction;
return engine;
}
106.
8. Run the application. The grid will appear as shown below.
107.
View [ASPX]
<%=Html.Syncfusion().Grid<Product>("Product_Grid","GridModel", column=>
{
column.Add(c =>
c.ProductID).HeaderText("Product ID");
column.Add(c =>
c.ProductName).HeaderText("Product Name");
column.Add(c =>
c.SupplierID).HeaderText("Supplier ID");
column.Add(c =>
c.UnitPrice).HeaderText("Unit Price");
column.Add(c =>
c.UnitsInStock).HeaderText("Units In Stock");
column.Add(c =>
c.UnitsOnOrder).HeaderText("Units On Order");
column.Add(c =>
c.ReorderLevel).HeaderText("Reorder Level");
})%>
View [cshtml]
@( Html.Syncfusion().Grid<Product>("Product_Grid","GridModel",
column=> { column.Add(c =>
c.ProductID).HeaderText("Product ID");
column.Add(c =>
c.ProductName).HeaderText("Product Name");
column.Add(c =>
c.SupplierID).HeaderText("Supplier ID");
column.Add(c =>
c.UnitPrice).HeaderText("Unit Price");
column.Add(c =>
c.UnitsInStock).HeaderText("Units In Stock");
column.Add(c =>
c.UnitsOnOrder).HeaderText("Units On Order");
column.Add(c =>
c.ReorderLevel).HeaderText("Reorder Level");
}))
4. Create a GridPropertiesModel in the Index method. Assign grid properties in this model
and pass the model from the controller to the view using the ViewData class as shown
below.
Controller
};
5. Create an action for the RowDataBound() action as given below to perform custom
formatting at the row level.
108.
Controller
[ChildActionOnly]
public void RowAction(GridTableRow<Product> row)
{
//Apply style to row whose UnitPrices are less than 20.
if (row.Data.UnitPrice < 20)
row.HtmlAttributes["style"] = "background-
color:#C3C3F2;color:#13771a;font-family:Verdana;font-weight:bold;";
6. Bind the action to GridPropertiesModel and pass the model to the view using the
ViewData method as given below:
109.
Controller
1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. Create the Grid control in the view and configure its properties.
4. Set the JSON action mode using the ActionMode method.
5. Set the RowDataBound handler name using the RowDataBound method.
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("Grid1")
.Caption("Orders")
.AutoFormat(Skins.Sandune)
.ActionMode(ActionMode.JSON)
.ClientSideEvents(events => {
events.RowDataBound("RowDataBoundHandler");
})
%>
View [cshtml]
@{ Html.Syncfusion().Grid<Order>("Grid1")
.Caption("Orders")
.AutoFormat(Skins.Sandune)
.ActionMode(ActionMode.JSON)
.ClientSideEvents(events => {
events.RowDataBound("RowDataBoundHandler");
}).Render();
7. In order to work with JSON mode actions, create a Post method for Index actions
and bind the data source to the grid as given in the following code sample.
110.
Controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new NorthwindDataContext().Orders.ToList();
return data.GridJSONActions<Order>();
}
JavaScript
1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. Add the following code in the Index.aspx file to create the Grid control in the view.
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("Grid1","GridModel", column
s => {
columns.Add(p => p.OrderID)
columns.Add(p => p.CustomerID)
columns.Add(p => p.EmployeeID);
columns.Add(P => P.ShipCountry);
columns.Add(p => p.OrderDate).Format("{0:dd-MM-yyyy}");
})%>
View [cshtml]
@( Html.Syncfusion().Grid<Order>("Grid1","GridModel", columns => {
columns.Add(p => p.OrderID)
columns.Add(p => p.CustomerID)
columns.Add(p => p.EmployeeID);
columns.Add(P => P.ShipCountry);
columns.Add(p => p.OrderDate).Format("{0:dd-MM-yyyy}");
})
)
[Controller]
public ActionResult Index()
{
ClientSideEvents eve = new ClientSideEvents();
eve.RowDataBound = "RowDataBoundHandler";
};
ViewData["GridModel"] = gridModel;
return View();
}
JavaScript
112.
7. In order to work with JSON mode, create a Post method for Index actions and bind the
data source to the grid as given in the following code.
113.
Controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new NorthwindDataContext().Orders.ToList();
return data.GridJSONActions<Order>();
}
Default value:
ActionMode.Server
Methods
Default value:
ActionMode.Server
Sample Link
To view the samples, follow the steps below:
1. Open the Grid sample browser from the dashboard (Refer to the Samples and Location
chapter).
Navigate to Grid.MVC > Formatting > Custom Formatting
System.Collections.ObjectModel.Collection<GridConditionalFormatDescript
or<Product>> cf = new
System.Collections.ObjectModel.Collection<GridConditionalFormatDescript
or<Product>>();
cf.Add(cFormat);
cf.Add(rowFormat);
%>
<%= Html.Syncfusion().Grid<Product>("ConditionalGrid")
.Datasource(Model)
.Caption("Products")
.Column(column =>
{
column.Add(c => c.ProductID).HeaderText("Product
ID").Width(100);
column.Add(c => c.ProductName).HeaderText("Product
Name");
column.Add(c => c.CategoryID).HeaderText("Category
ID").Width(100);
column.Add(c => c.UnitPrice).HeaderText("Unit
Price").Format("{0:C2}").Width(100);
column.Add(c => c.UnitsInStock).HeaderText("Units In
Stock").Width(100);
})
.EnablePaging()
.EnableSorting()%>
115.
116.
View [cshtml]
@{ GridDataCondition<Product> condition1 = new
GridDataCondition<Product>(c => c.UnitPrice) { ConditionType =
GridDataConditionType.GreaterThan, Value = 30 };
GridDataCondition<Product> condition2 = new
GridDataCondition<Product>(c => c.UnitsInStock) { ConditionType =
GridDataConditionType.GreaterThan, Value = 50 };
GridConditionalFormatDescriptor<Product> cFormat = new
GridConditionalFormatDescriptor<Product>();
cFormat.Name = "c1";
cFormat.ApplyStyleToColumn = "ProductName";
cFormat.Conditions.Add(condition1);
cFormat.Conditions.Add(condition2);
cFormat.Cell.HtmlAttributes["style"] = "background-color:
#1BA1E2 ;Color:#FFFFFF;";
System.Collections.ObjectModel.Collection<GridConditionalFormatDescript
or<Product>> cf = new
System.Collections.ObjectModel.Collection<GridConditionalFormatDescript
or<Product>>();
cf.Add(cFormat);
cf.Add(rowFormat);
}
@{ Html.Syncfusion().Grid<Product>("ConditionalGrid")
.Datasource(Model)
.Caption("Products")
.Column(column =>
{
column.Add(c => c.ProductID).HeaderText("Product
ID").Width(100);
column.Add(c => c.ProductName).HeaderText("Product
Name");
column.Add(c => c.CategoryID).HeaderText("Category
ID").Width(100);
column.Add(c => c.UnitPrice).HeaderText("Unit
Price").Format("{0:C2}").Width(100);
column.Add(c => c.UnitsInStock).HeaderText("Units In
Stock").Width(100);
})
.ConditionalFormats(c => { c.Add(cf); })
.EnablePaging()
.EnableSorting()
.Render();
}
private Collection<GridConditionalFormatDescriptor<Product>>
ConditionFormats
{
get
{
GridDataCondition<Product> condition1 = new
GridDataCondition<Product>(c => c.UnitPrice) { ConditionType =
GridDataConditionType.GreaterThan, Value = 30 };
GridDataCondition<Product> condition2 = new
GridDataCondition<Product>(c => c.UnitsInStock) { ConditionType =
GridDataConditionType.GreaterThan, Value = 50 };
GridConditionalFormatDescriptor<Product> cFormat = new
GridConditionalFormatDescriptor<Product>();
cFormat.Name = "c1";
cFormat.ApplyStyleToColumn = "ProductName";
cFormat.Conditions.Add(condition1);
cFormat.Conditions.Add(condition2);
cFormat.Cell.HtmlAttributes["style"] = "background-
color: #1BA1E2 ;Color:#FFFFFF;";
Collection<GridConditionalFormatDescriptor<Product>> cf
= new Collection<GridConditionalFormatDescriptor<Product>>();
cf.Add(cFormat);
cf.Add(rowFormat);
return cf;
}
}
/// <summary>
/// Used to bind the grid.
/// </summary>
/// <returns>View page; it displays the grid.</returns>
public ActionResult Index()
{
var data = new NorthwindDataContext().Products.ToList();
return View(data);
}
6. In order to work with conditional formatting actions after grid post action, create a Post
method for Index actions , bind the data source to the grid and pass the data to the
view as a ActionResult as given in the following code.
Controller
/// <summary>
/// Paging/sorting requests are mapped to this method. This
method invokes the HtmlActionResult
/// from the grid. Required response is generated.
/// </summary>
/// <param name="args">Contains paging properties. </param>
/// <returns>
/// HtmlActionResult returns the data displayed on the grid.
/// </returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new
NorthwindDataContext().Products.ToList();
ActionResult result = data.GridActions<Product>();
var engineSource = result as GridHtmlActionResult<Product>;
engineSource.GridModel.ConditionalFormats =
this.ConditionFormats;
return engineSource; }
1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. Add the following code in the Index.aspx file to create the Grid control in the view.
120.
View [ASPX]
Price").Format("{0:C2}").Width(100);
column.Add(c => c.UnitsInStock).HeaderText("Units
In Stock").Width(100);
})%>
View [cshtml]
@( Html.Syncfusion().Grid<Product>("ConditionalGrid", column =>{
column.Add(c => c.ProductID).HeaderText("Product
ID").Width(100);
column.Add(c => c.ProductName).HeaderText("Product Name");
column.Add(c => c.CategoryID).HeaderText("Category
ID").Width(100);
column.Add(c => c.UnitPrice).HeaderText("Unit
Price").Format("{0:C2}").Width(100);
column.Add(c => c.UnitsInStock).HeaderText("Units In
Stock").Width(100);
}))
4. Create an action for the CondtionalFormats() action as shown below to perform condtional
formatting for grid contents.
121.
Controller
private Collection<GridConditionalFormatDescriptor<Product>>
ConditionFormats
{
get
{
GridDataCondition<Product> condition1 = new
GridDataCondition<Product>(c => c.UnitPrice) { ConditionType =
GridDataConditionType.GreaterThan, Value = 30 };
GridDataCondition<Product> condition2 = new
GridDataCondition<Product>(c => c.UnitsInStock) { ConditionType =
GridDataConditionType.GreaterThan, Value = 50 };
GridConditionalFormatDescriptor<Product> cFormat = new
GridConditionalFormatDescriptor<Product>();
cFormat.Name = "c1";
cFormat.ApplyStyleToColumn = "ProductName";
cFormat.Conditions.Add(condition1);
cFormat.Conditions.Add(condition2);
cFormat.Cell.HtmlAttributes["style"] = "background-
color: #1BA1E2 ;Color:#FFFFFF;";
rowFormat.Conditions.Add(condition3);
rowFormat.Cell.HtmlAttributes["style"] =
"background:#F9AE17;color:white;";
Collection<GridConditionalFormatDescriptor<Product>> cf
= new Collection<GridConditionalFormatDescriptor<Product>>();
cf.Add(cFormat);
cf.Add(rowFormat);
return cf;
}
}
/// <summary>
/// Used to bind the grid.
/// </summary>
/// <returns>View page; it displays the grid.</returns>
public ActionResult Index()
{
GridPropertiesModel<Product> model = new
GridPropertiesModel<Product>();
model.DataSource = new
NorthwindDataContext().Products.ToList();
model.Caption = "Product";
model.AllowPaging = true;
model.AllowSorting = true;
model.ConditionalFormats = this.ConditionFormats;
ViewData["ConditionalGrid"] = model;
return View();
}
6. In order to work with conditional formatting actions after grid post action, create a Post
method for Index actions , bind the data source to the grid and pass the data to the view as
a ActionResult as given in the following code.
Controller
/// <summary>
/// Paging/sorting requests are mapped to this method. This
method invokes the HtmlActionResult
/// from the grid. Required response is generated.
/// </summary>
/// <param name="args">Contains paging properties. </param>
/// <returns>
/// HtmlActionResult returns the data displayed on the grid.
/// </returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new
NorthwindDataContext().Products.ToList();
ActionResult result = data.GridActions<Product>();
var engineSource = result as GridHtmlActionResult<Product>;
engineSource.GridModel.ConditionalFormats =
this.ConditionFormats;
return engineSource;
}
4.10 Summaries
The Grid control allows you to display summaries. Summaries let you derive additional
information from your data like averages, maximums, summations, counts, and more.
For instance, you can get the number of records or maximum value and so on. They display the
calculation results in separate display rows. The summary values are calculated using Linq
expressions.
Summary Rows
The GridPropertiesModel.SummaryRows manages the collection of summary rows for the grid.
It is the GridSummaryRowDescriptorCollection that manages the summaries for the given
data source containing one entry for each summary. Each GridSummaryRowDescriptor in this
collection has a name that identifies the SummaryRowDescriptors for which summaries are
calculated for and a SummaryType property that defines the type of calculations to be
performed. Possible options for SummaryType are: Count, BooleanAggregate,
Int32Aggregate, DoubleAggregate.
Properties
SummaryType
.Count
Methods
ptors) collection.
specified index.
GridSummaryRo
wDescriptor in
the collection.
1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. In the view you can use its Model property in Datasource() to bind the data source.
View [ASPX]
<%=Html.Syncfusion().Grid<Student>("StudentGrid")
.Datasource(Model)
.Caption("Orders")
.EnablePaging()
.EnableSorting()
.AutoFormat(Skins.Sandune)
.Column( column => {
column.Add(p =>
p.UniversityCode).HeaderText("University Code");
column.Add(p => p.Title).HeaderText("Course
Title");
column.Add(P => P.Duration);
column.Add(p =>
p.CourseFees).Format("{CourseFees:c}").HeaderText("Course
Fees");
column.Add(p => p.CGPA);
})
%>
View [cshtml]
@{ Html.Syncfusion().Grid<Student>("StudentGrid")
.Datasource(Model)
.Caption("Orders")
.EnablePaging()
.EnableSorting()
.AllowSummaries(true)
.AutoFormat(Skins.Sandune)
.Column( column => {
column.Add(p =>
p.UniversityCode).HeaderText("University Code");
column.Add(p => p.Title).HeaderText("Course
Title");
column.Add(P => P.Duration);
column.Add(p =>
p.CourseFees).Format("{CourseFees:c}").HeaderText("Course
Fees");
column.Add(p => p.CGPA);
}).Render();
}
Controller
Controller
Controller
maxRow.Title = "Largest";
Controller
Note: In this sample, SummaryRows are defined inside the private property “SummaryRows”
8. Pass the GridPropertiesModel to the view using the ViewData() method. Use the
grid’s ID as the key in ViewData.
Controller
// Pass the GridPropertiesModel to the grid using GridID. Here
StudentGrid is the grid's ID.
ViewData["StudentGrid"] = gridModel;
9. If you enable the paging and sorting features, rebind the SummaryRow property again
in Post actions as given below.
Controller
/// <summary>
/// Paging/sorting requests are mapped to this method. This
method invokes the HtmlActionResult
/// from the grid. The required response is generated.
/// </summary>
/// <param name="args">Contains paging properties. </param>
/// <returns>
/// HtmlActionResult returns the data displayed in the grid.
/// </returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new
StudentDataContext().AutoFormatStudent.Skip(0).Take(20).ToList();
return result;
}
10. Run the sample. The grid will appear as shown below.
1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. Add the following code in the Index.aspx file to create the Grid control in the view.
123.
View [ASPX]
<%=Html.Syncfusion().Grid<Student>("StudentGrid",
"GridModel", column =>
{
column.Add(p =>
p.UniversityCode).HeaderText("University Code");
column.Add(p =>
p.Title).HeaderText("Course Title");
column.Add(P => P.Duration);
column.Add(p =>
p.CourseFees).Format("{CourseFees:c}").HeaderText("Course
Fees");
column.Add(p => p.CGPA);
}) %>
View [cshtml]
Controller
Controller
125. Finally add the summary row to the grid using SummaryRows.
Controller
ViewData["GridModel"] = gridModel;
Note: In this sample, summary rows are defined inside the private property “SummaryRows”.
126. If you enable the paging and sorting features, rebind the SummaryRow property again in
Post actions as given below.
Controller
/// <summary>
/// Paging/sorting requests are mapped to this method. This
method invokes the HtmlActionResult
/// from the grid. The required response is generated.
/// </summary>
/// <param name="args">Contains paging properties. </param>
/// <returns>
/// HtmlActionResult returns the data displayed in the grid.
/// </returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new
StudentDataContext().AutoFormatStudent.Skip(0).Take(20).ToList();
return result;
}
127. Run the sample. The grid will look like this:
Figure 170: Grid with Summary Rows
Sample Link
To view the samples, follow the steps below:
1. Open the Grid sample browser from the dashboard (Refer to the Samples and Location
chapter).
2. Navigate to Grid.MVC > Summary > Summaries
1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. Create the Grid control in the view and configure its properties.
4. Set the JSON action mode using the ActionMode method.
5. To enable summaries, use the AllowSummaries method.
128.
View[ASPX]
<%=Html.Syncfusion().Grid<Order>("Grid1")
.Caption("Orders")
.AutoFormat(Skins.Sandune)
.ActionMode(ActionMode.JSON)
.Summaries(summary => {
summary.AllowSummaries(true)
.Add((IEnumerable<GridSummaryRowDescriptor>)ViewData["SummaryRowDescrip
tors"]);
})
.Column( columns => {
columns.Add(p => p.OrderID);
columns.Add(p => p.CustomerID);
columns.Add(p => p.EmployeeID);
columns.Add(P => P.ShipCountry);
columns.Add(p => p.OrderDate).Format("{0:dd-MM-yyyy}");
})
%>
View [cshtml]
@{ Html.Syncfusion().Grid<Order>("Grid1")
.Caption("Orders")
.AutoFormat(Skins.Sandune)
.ActionMode(ActionMode.JSON)
.Summaries(summary => {
summary.AllowSummaries(true)
.Add((IEnumerable<GridSummaryRowDescriptor>)ViewData["SummaryRowDescrip
tors"]);
})
.Column( columns => {
columns.Add(p => p.OrderID);
columns.Add(p => p.CustomerID);
columns.Add(p => p.EmployeeID);
columns.Add(P => P.ShipCountry);
columns.Add(p => p.OrderDate).Format("{0:dd-MM-yyyy}");
}).Render();
}
Controller
GridSummaryRowDescriptor maxRow = new
GridSummaryRowDescriptor("Largest");
/// Title displayed in the summary Row.
maxRow.Title = "Largest";
/// Custom text which can be prefixed with the
maxCGPA summary.
maxCGPA.Prefix = "Max:";
/// Summary columns are added into the Summary
row.
maxRow.SummaryColumns.Add(maxCGPA);
Controller
ViewData[“SummaryRowDescriptors”] =
this.SummaryCollection;
10. If you enable the paging and sorting features, rebind the SummaryRow property again
in Post action as given below.
131.
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new
StudentDataContext().AutoFormatStudent.Skip(0).Take(20).ToList();
ActionResult result = data.GridJSONActions<Student>();
var engineSource = result as GridJSONActionResult<Student>;
// Rebinding the SummaryRows.
foreach (GridSummaryRowDescriptor summaryRow in
this.SummaryCollection)
engineSource.GridModel.SummaryRows.Add(summaryRow);
return result;
}
11. Run the application. The grid will appear as shown below.
1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. Add the following code in the Index.aspx file to create the Grid control in the view.
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("Grid1","GridModel", column
s => {
columns.Add(p => p.OrderID)
columns.Add(p => p.CustomerID)
columns.Add(p => p.EmployeeID);
columns.Add(P => P.ShipCountry);
columns.Add(p => p.OrderDate).Format("{0:dd-MM-yyyy}");
})%>
View [cshtml]
@( Html.Syncfusion().Grid<Order>("Grid1","GridModel", columns => {
columns.Add(p => p.OrderID)
columns.Add(p => p.CustomerID)
columns.Add(p => p.EmployeeID);
columns.Add(P => P.ShipCountry);
columns.Add(p => p.OrderDate).Format("{0:dd-MM-yyyy}");
}))
[Controller]
public ActionResult Index()
{
GridPropertiesModel<Order> gridModel = new
GridPropertiesModel<Order>()
{
Caption = "Orders",
AutoFormat = Syncfusion.Mvc.Shared.Skins.Sandune,
AllowSummaries = true,
ActionMode = ActionMode.JSON
};
ViewData["GridModel"] = gridModel;
return View();
}
134. Finally, add the summary row to the grid using SummaryRows.
Controller
ViewData["GridModel"] = gridModel;
8. If you enable the paging and sorting features, rebind the SummaryRow property again
in Post actions as given below.
135.
Controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new
StudentDataContext().AutoFormatStudent.Skip(0).Take(20).ToList();
ActionResult result = data.GridActions<Student>();
var engineSource = result as GridHtmlActionResult<Student>;
// Rebinding the SummaryRows.
foreach (GridSummaryRowDescriptor summaryRow in
this.SummaryCollection)
engineSource.GridModel.SummaryRows.Add(summaryRow);
return result;
}
4.11 Scrolling
Essential Grid’s scrolling feature allows you to scroll through the grid manually.
Another feature that we have implemented under scrolling is virtual scrolling.
4.11.1 Scrolling
Essential Grid now allows you to specify the required width and height for a grid. You can scroll
through the grid manually. Also, the width property in the ColumnBuilder can be used to set the
width for individual grid columns in both design time and run time.
Properties
height of grid.
Methods
Essential Grid’s scrolling feature allows you to scroll through the grid manually.
Another feature that we have implemented under scrolling is that of virtual scrolling.
<%=Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.PageSettings(page => page.PageSize(20))
.EnableSorting()
.AutoFormat(Skins.Sandune)
.Column( columns => {
columns.Add(p => p.OrderID).HeaderText("Order
ID");
columns.Add(p =>
p.CustomerID).HeaderText("Customer ID");
columns.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship
Country");
columns.Add(p => p.OrderDate).HeaderText("Order
Date").Format("{0:dd-MM-yyyy}");
})
%>
137.
View [cshtml]
@{ Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.PageSettings(page => page.PageSize(20))
.EnableSorting()
.AutoFormat(Skins.Sandune)
.Column( columns => {
columns.Add(p => p.OrderID).HeaderText("Order
ID");
columns.Add(p =>
p.CustomerID).HeaderText("Customer ID");
columns.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship
Country");
columns.Add(p => p.OrderDate).HeaderText("Order
Date").Format("{0:dd-MM-yyyy}");
}).Render();
}
Date").Format("{0:dd-MM-yyyy}");
})
%>
139.
View [cshtml]
@{ Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.PageSettings(page => page.PageSize(20))
.EnableSorting()
.AutoFormat(Skins.Sandune)
.Column( columns => {
columns.Add(p => p.OrderID).HeaderText("Order
ID").Width(150);
columns.Add(p =>
p.CustomerID).HeaderText("Customer ID").Width(200);
columns.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship
Country");
columns.Add(p => p.OrderDate).HeaderText("Order
Date").Format("{0:dd-MM-yyyy}");
}).Render();
}
5. Enable the scrolling feature by the AllowScrolling() method. Specify the grid width and
height by using Width() and Height().
140.
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.PageSettings(page => page.PageSize(20))
.EnableSorting()
.Scrolling( scroll => {
scroll.AllowScrolling(true);
scroll.Height(400);
scroll.Width(900);
})
.AutoFormat(Skins.Sandune)
.Column( columns => {
columns.Add(p => p.OrderID).HeaderText("Order
ID").Width(150);
columns.Add(p => p.CustomerID).HeaderText("Customer
ID").Width(200);
columns.Add(p => p.EmployeeID).HeaderText("Employee
ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship
Country");
columns.Add(p => p.OrderDate).HeaderText("Order
Date").Format("{0:dd-MM-yyyy}");
})
%>
View [cshtml]
@{ Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.PageSettings(page => page.PageSize(20))
.EnableSorting()
.Scrolling( scroll => {
scroll.AllowScrolling(true);
scroll.Height(400);
scroll.Width(900);
})
.AutoFormat(Skins.Sandune)
.Column( columns => {
columns.Add(p => p.OrderID).HeaderText("Order
ID").Width(150);
columns.Add(p => p.CustomerID).HeaderText("Customer
ID").Width(200);
columns.Add(p => p.EmployeeID).HeaderText("Employee
ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship
Country");
columns.Add(p => p.OrderDate).HeaderText("Order
Date").Format("{0:dd-MM-yyyy}");
}).Render();
}
1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. Add the following code in the Index.aspx file to create the Grid control in the view.
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("OrderGrid","GridModel", columns => {
columns.Add(p => p.OrderID).HeaderText("Order
ID");
columns.Add(p =>
p.CustomerID).HeaderText("Customer ID");
columns.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
columns.Add(P =>
P.ShipCountry).HeaderText("Ship Country");
columns.Add(p => p.OrderDate).HeaderText("Order
Date").Format("{0:dd-MM-yyyy}");
})%>
View [cshtml]
@( Html.Syncfusion().Grid<Order>("OrderGrid","GridModel",
columns => {
columns.Add(p => p.OrderID).HeaderText("Order
ID");
columns.Add(p =>
p.CustomerID).HeaderText("Customer ID");
columns.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
columns.Add(P =>
P.ShipCountry).HeaderText("Ship Country");
columns.Add(p => p.OrderDate).HeaderText("Order
Date").Format("{0:dd-MM-yyyy}");
}))
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("OrderGrid","GridModel",
columns => {
columns.Add(p => p.OrderID).HeaderText("Order
ID").Width(150);
columns.Add(p =>
p.CustomerID).HeaderText("Customer ID").Width(200);
columns.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship
Country");
columns.Add(p => p.OrderDate).HeaderText("Order
Date").Format("{0:dd-MM-yyyy}");
})%>
View [cshtml]
@( Html.Syncfusion().Grid<Order>("OrderGrid","GridModel",
columns => {
columns.Add(p => p.OrderID).HeaderText("Order
ID").Width(150);
columns.Add(p =>
p.CustomerID).HeaderText("Customer ID").Width(200);
columns.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship
Country");
columns.Add(p => p.OrderDate).HeaderText("Order
Date").Format("{0:dd-MM-yyyy}");
}))
Controller
6. Specify the grid width and height by using the Width and Height properties.
Controller
Default value is
VirtualScrollMode.No
rmal
Scrolling Methods
<%=Html.Syncfusion().Grid<EditableOrder>("Grid")
.Datasource(Model)
.Column(column =>
{
column.Add(p => p.OrderID).HeaderText("Order
ID");
column.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
column.Add(p =>
p.CustomerID).HeaderText("Customer ID");
column.Add(p => p.ShipCountry).HeaderText("Ship
Country");
column.Add(p => p.OrderDate).HeaderText("Order
Date").Format("{OrderDate:MM/dd/yyyy}");
column.Add(p => p.Freight).HeaderText("Freight");
})
----
.Scrolling(scroll=>{
scroll.AllowVirtualScrolling(true); // Enabling
virtual scrolling.
})
----
%>
View[cshtml]
@{
Html.Syncfusion().Grid<EditableOrder>("Grid")
.Datasource(Model)
.Column(column =>
{
column.Add(p => p.OrderID).HeaderText("Order
ID");
column.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
column.Add(p =>
p.CustomerID).HeaderText("Customer ID");
column.Add(p => p.ShipCountry).HeaderText("Ship
Country");
column.Add(p => p.OrderDate).HeaderText("Order
Date").Format("{OrderDate:MM/dd/yyyy}");
column.Add(p => p.Freight).HeaderText("Freight");
})
----
.Scrolling(scroll=>{
scroll.AllowVirtualScrolling(true); // Enabling
virtual scrolling.
})
----
.Render()
/// <summary>
/// Used for rendering the grid initially.
/// </summary>
/// <returns>View page; it displays the grid.</returns>
public ActionResult Index()
{
IEnumerable data = new
NorthwindDataContext().Orders.Take(200).ToList();
return View(data);
}
5. In order to work with filter actions, create a Post method for Index actions and bind the data
source to the grid as shown in the following code:
142.
Controller
<summary>
6. Run the application. You can see the grid loaded with the initial items and upon scrolling the
required data is loaded.
View[ASPX]
View[cshtml]
)}
Controller
/// <summary>
/// Used for rendering the grid initially.
/// </summary>
/// <returns>View page, it displays the Grid</returns>
public ActionResult Index()
{
GridPropertiesModel<Order> gridModel = new
GridPropertiesModel<Order>()
{
DataSource = new
NorthwindDataContext().Orders.Take(200).ToList(),
Caption = "Orders",
-----
};
gridModel.Scrolling.AllowVirtualScrolling = true; //
Enabling virtual scrolling.
ViewData["GridModel"] = gridModel;
return View();
}
/// <summary>
/// Paging/editing/filtering requests are mapped to this
method. This method invokes the HtmlActionResult
/// from the grid and the required response is generated.
/// </summary>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new
NorthwindDataContext().Orders.Take(200).ToList();
return data.GridActions<Order>();
148. Run the application. You can see the grid with the initial records loaded and upon
scrolling, the required data is loaded.
<%=Html.Syncfusion().Grid<EditableOrder>("Grid")
.Datasource(Model)
.Column(column =>
{
column.Add(p => p.OrderID).HeaderText("Order
ID");
column.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
column.Add(p =>
p.CustomerID).HeaderText("Customer ID");
column.Add(p => p.ShipCountry).HeaderText("Ship
Country");
column.Add(p => p.OrderDate).HeaderText("Order
Date").Format("{OrderDate:MM/dd/yyyy}");
column.Add(p => p.Freight).HeaderText("Freight");
})
----
.Scrolling(scroll=>{
scroll.AllowVirtualScrolling(true)
%>
View[cshtml]
@{
Html.Syncfusion().Grid<EditableOrder>("Grid")
.Datasource(Model)
.Column(column =>
{
column.Add(p => p.OrderID).HeaderText("Order
ID");
column.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
column.Add(p =>
p.CustomerID).HeaderText("Customer ID");
column.Add(p => p.ShipCountry).HeaderText("Ship
Country");
column.Add(p => p.OrderDate).HeaderText("Order
Date").Format("{OrderDate:MM/dd/yyyy}");
column.Add(p => p.Freight).HeaderText("Freight");
})
----
.Scrolling(scroll=>{
scroll.AllowVirtualScrolling(true)
----
.Render()
/// <summary>
/// Used for rendering the grid initially.
/// </summary>
/// <returns>View page; it displays the grid.</returns>
public ActionResult Index()
{
IEnumerable data = new
NorthwindDataContext().Orders.Take(200).ToList();
return View(data);
}
6. In order to work with filter actions, create a Post method for Index actions and bind the data
source to the grid as shown in the following code.
Controller
<summary>
/// Paging/editing/filtering requests are mapped to this
method. This method invokes the HtmlActionResult
/// from the grid and the required response is generated.
/// </summary>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new
NorthwindDataContext().Orders.Take(200).ToList();
return data.GridActions<Order>();
7. Run the application. You can see the grid with the initial records loaded and on scrolling the
required data is loaded.
View[ASPX]
View[cshtml]
Controller
/// <summary>
/// Used for rendering the grid initially.
/// </summary>
/// <returns>View page; it displays the grid.</returns>
public ActionResult Index()
{
GridPropertiesModel<Order> gridModel = new
GridPropertiesModel<Order>()
{
DataSource = new
NorthwindDataContext().Orders.Take(200).ToList(),
Caption = "Orders",
-----
};
gridModel.Scrolling.AllowVirtualScrolling = true;
gridModel.Scrolling.VirtualScrollMode =
VirtualScrollMode.Facebook; // Configuring virtual scroll modes.
ViewData["GridModel"] = gridModel;
return View();
}
/// <summary>
/// Paging/editing/filtering requests are mapped to this
6. Run the application. You can see the grid with the initial records loaded and during
scrolling, the required data is loaded.
4.12 Selection
You can select one or more rows/records of the Grid using some keyboard keys. Before
selecting, you need to enable this feature by setting the Selection property to True.
Properties
y b-properties
associated
Methods
After enabling the AllowSelection property, select any one row at run time. Now, by holding
CTRL, you will be able to select other rows also using the left mouse button as in the image
below.
For multiple selections, use SHIFT+arrow keys for continuous selection of consecutive
rows.
Press CTRL and left-click to select random rows for multiple selections.
Selection is enabled by default.
2. CTRL+mouse-click selection.
149.
4. Row selection.
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("Grid1")
.Datasource((IEnumerable<Order>)ViewData["ToggleGrid"])
.Caption("Orders")
.Column(column =>
{
column.Add(p =>
p.OrderID).HeaderText("Order ID");
column.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
column.Add(p =>
p.CustomerID).HeaderText("Customer ID");
column.Add(p =>
p.OrderDate).HeaderText("Order Date").Format("{OrderDate:MM/dd/yyyy}");
column.Add(p =>
p.Freight).HeaderText("Freight");
})
.EnablePaging()
.AutoFormat(Skins.Sandune)
.RowsSelectionMode(RowsSelectionMode.Toggle)
%>
View [cshtml]
@{ Html.Syncfusion().Grid<Order>("Grid1")
.Datasource((IEnumerable<Order>)ViewData["ToggleGrid"])
.Caption("Orders")
.Column(column =>
{
column.Add(p =>
p.OrderID).HeaderText("Order ID");
column.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
column.Add(p =>
p.CustomerID).HeaderText("Customer ID");
column.Add(p =>
p.OrderDate).HeaderText("Order Date").Format("{OrderDate:MM/dd/yyyy}");
column.Add(p =>
p.Freight).HeaderText("Freight");
})
.EnablePaging()
.AutoFormat(Skins.Sandune)
.RowsSelectionMode(RowsSelectionMode.Toggle)
.Render();
}
4. Set the data source in the action and render the view.
[Controller]
/// <summary>
/// Used for rendering the grid initially.
/// </summary>
/// <returns>View page; it displays the grid.</returns>
public ActionResult Index()
{
ViewData["ToggleGrid"] = new
NorthwindDataContext().Orders.ToList();
return View();
}
5. Run the application and select any row in the grid. The grid will appear as shown below.
If you click on the selected row, the selected row will be unselected as shown in the following
screenshot.
1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. Add the following code in the HomeController.cs file to create the Grid control in the view.
[Controller]
/// <summary>
/// Used for rendering the grid initially.
/// </summary>
/// <returns>View page; it displays the Grid.</returns>
public ActionResult OrderGrid()
{
ViewData["GridModel"] = gridModel;
return View();
View [ASPX]
})
%>
View [cshtml]
@( Html.Syncfusion().Grid<Order>("Grid1", "GridModel", column =>
{
column.Add(p =>
p.OrderID).HeaderText("Order ID");
column.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
column.Add(p =>
p.CustomerID).HeaderText("Customer ID");
column.Add(p =>
p.OrderDate).HeaderText("Order Date").Format("{OrderDate:MM/dd/yyyy}");
column.Add(p =>
p.Freight).HeaderText("Freight");
}))
5. Run the application and select any row in the grid. The grid will appear as shown below.
If you click on the selected row, the selected row will be unselected as shown in the following
screenshot.
This feature allows you to select multiple rows (using jQuery UI Selectable) and drag and drop
the selected rows to any other element which is specified using the TargetHtmlElementId
property of the grid.
Properties
RowsDroppingMappe This property sets the string Any string value AllowRowsDragging
r mapping string. To update the
source grid while dropping the
rows, if you need one Action
means you can give here.
Methods
Events
OnRowDropped The event which calls the handler after dropped operation. By Event,
this event you can update your own target element by using
Data
ajax post.
To enable the row drag-and-drop feature you need to perform the following.
1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. In the view you can use its Model property in Datasource() to bind the data source.
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("GridSrc")
.Datasource((IEnumerable<Order>)ViewData["data"])
.Caption("First Grid Order")
.Column(column =>
{
column.Add(p =>
p.OrderID).HeaderText("Order ID");
column.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
column.Add(p =>
p.CustomerID).HeaderText("Customer ID");
})
.AllowRowsDragging(true)
.AllowDragAndDrop(false)
.TargetHtmlElementId("#GridDest")
.RowsDraggingMode(DragandDropMode.GhostRows)
.AutoFormat(Skins.Midnight)
.RowsDroppingMapper("Dragged")
.ClientSideEvents(events => {
events.OnRowDropping("OnDropping");
events.OnRowDropped("DroppedTarget");
})
%>
View [cshtml]
@{ Html.Syncfusion().Grid<Order>("GridSrc")
.Datasource((IEnumerable<Order>)ViewData["data"])
.Caption("First Grid Order")
.Column(column =>
{
column.Add(p =>
p.OrderID).HeaderText("Order ID");
column.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
column.Add(p =>
p.CustomerID).HeaderText("Customer ID");
})
.AllowRowsDragging(true)
.AllowDragAndDrop(false)
.TargetHtmlElementId("#GridDest")
.RowsDraggingMode(DragandDropMode.GhostRows)
.AutoFormat(Skins.Midnight)
.RowsDroppingMapper("Dragged")
.ClientSideEvents(events => {
events.OnRowDropping("OnDropping");
events.OnRowDropped("DroppedTarget");
}).Render();
}
2. Set the data source in the Index action and render the view.
153.
[Controller]
/// <summary>
/// Used for rendering the grid initially.
/// </summary>
/// <returns>View page; it displays the grid.</returns>
public ActionResult Index()
{
ViewData["data"] = GridOrders.SrcOrders;
ViewData["dataDest"] = GridOrders.DestOrders;
if (ControllerContext.HttpContext.Request.IsAjaxRequest())
{
return PartialView("DragResetPartialView",
this.ViewData);
}
return View();
Now you can select any rows in your grid and drop them into any other target element. In the
sample, you set the target element as another grid. Please refer to example above. The following
screenshot shows rows being dropped in another element.
[Controller]
/// <summary>
/// Used for rendering the grid initially.
/// </summary>
/// <returns>View page; it displays the grid.</returns>
public ActionResult OrderGrid()
{
GridPropertiesModel<Order> Srcmodel= new
GridPropertiesModel<Order>()
{
DataSource = GridOrders.SrcOrders,
Caption = "First Grid Order",
AllowRowsDragging = true,
AllowDragAndDrop = false,
TargetHtmlElementId = "#GridDest",
RowsDraggingMode = DragandDropMode.GhostRows,
AutoFormat = Skins.Midnight,
RowsDroppingMapper = "Dragged",
OnRowDropping = "OnDropping",
OnRowDropped="DroppedTarget"
};
ViewData["SrcGrid"] = Srcmodel;
Return View();
}
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("GridSrc","SrcGrid",column =>
{
column.Add(p =>
p.OrderID).HeaderText("Order ID");
column.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
column.Add(p =>
p.CustomerID).HeaderText("Customer ID");
})
%>
View [cshtml]
@( Html.Syncfusion().Grid<Order>("GridSrc","SrcGrid",column =>
{
column.Add(p =>
p.OrderID).HeaderText("Order ID");
column.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
column.Add(p =>
p.CustomerID).HeaderText("Customer ID");
}))
Now you can select any rows in your grid and drop them into any other target element. In the
sample, you set the target element as another grid. Please refer to example above. The following
screenshot shows rows being dropped in another element.
Sample Link
To view the samples, follow the steps below:
1. Open the Grid sample browser from the dashboard (Refer to the Samples and Location
chapter).
2. Navigate to Grid.MVC > Drag-and-Drop > Grid-to-Grid
Properties
Methods
Method Parameter Return Description
type type
Droppable Boolean IGridBuilder This property sets your Grid as
Droppable.
To represent class:
“.TargetClassname”
Events
OnGridRowsDropEvent The event which calls the handler after dropped Event,
operation. By this event you can update your own
Data,
target element by using ajax post. In this event you are
passing the Grid object, Json Record of the selected DragElement
row and the element that is dropped.
To enable the drag any other element and drop it into grid rows feature you need to perform the
following:
1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. In the view you can use its Model property in DataSource to bind the data source.
View [ASPX]
<%=Html.Syncfusion().Grid<ShoppingCart>("Grid1")
.Datasource((IEnumerable<ShoppingCart>)ViewData["CartGrid"])
.Caption("Shopping Cart")
.Column(column =>
{
column.Add(p =>
p.ProductID).HeaderText("Product ID");
column.Add(p =>
p.Count).HeaderText("Count");
column.Add(p =>
p.Price).HeaderText("Price").Format("${Price:0.00}");
})
.Droppable(true)
.ElementtoDrag(".ItemsDraggable")
.AutoFormat(Skins.Marble)
.EnableHighlighting(true)
.EnableSelectionOnDragging(true)
.ClientSideEvents(events=>{
events.OnGridRowsDropEvent("DroppedTarget");
})
%>
View [cshtml]
@{ Html.Syncfusion().Grid<ShoppingCart>("Grid1")
.Datasource((IEnumerable<ShoppingCart>)ViewData["CartGrid"])
.Caption("Shopping Cart")
.Column(column =>
{
column.Add(p =>
p.ProductID).HeaderText("Product ID");
column.Add(p =>
p.Count).HeaderText("Count");
column.Add(p =>
p.Price).HeaderText("Price").Format("${Price:0.00}");
})
.Droppable(true)
.ElementtoDrag(".ItemsDraggable")
.AutoFormat(Skins.Marble)
.EnableHighlighting(true)
.EnableSelectionOnDragging(true)
.ClientSideEvents(events=>{
events.OnGridRowsDropEvent("DroppedTarget");
}).Render();
[Controller]
/// <summary>
/// Used for rendering the grid initially.
/// </summary>
/// <returns>View page; it displays the grid.</returns>
public ActionResult Index()
{
ViewData["CartGrid"] =
ShoppingCartOrders.CartOrders.Where(p => p.Count > 0).ToList();
return View();
}
[Controlller]
/// <summary>
/// Used for rendering the grid initially.
/// </summary>
/// <returns>View page; it displays the grid.</returns>
public ActionResult OrderGrid()
{
GridPropertiesModel<ShoppingCart> gridModel = new
GridPropertiesModel<ShoppingCart>()
{
ViewData["GridModel"] = gridModel;
return View();
View [ASPX]
<%=Html.Syncfusion().Grid<ShoppingCart>(
"Grid1", "GridModel",column =>
{
column.Add(p =>
p.ProductID).HeaderText("Product ID");
column.Add(p =>
p.Count).HeaderText("Count");
column.Add(p =>
p.Price).HeaderText("Price").Format("${Price:0.00}");
})
View [cshtml]
@( Html.Syncfusion().Grid<ShoppingCart>(
"Grid1", "GridModel",column =>
{
column.Add(p =>
p.ProductID).HeaderText("Product ID");
column.Add(p =>
p.Count).HeaderText("Count");
column.Add(p =>
p.Price).HeaderText("Price").Format("${Price:0.00}");
})
The following screenshot shows that any element within the ElementtoDrag Selector can be
dragged. Here the items are set as draggable elements.
The following screenshot shows the dropped grid that is updated using the event.
Edit Record F2
Key Configuration: All keyboard shortcuts can be configured using the KeyConfigurator
property in the GridPropertiesModel.
Note: Keyboard shortcuts work only when the grid is in focus. Focus can be set by clicking on
any part of the grid or by using the shortcut of the Focus Key action.
In the Mozilla Firefox browser, focus can be identified by the dotted lines around the Grid object.
View [ASPX]
<%=Html.Syncfusion().Syncfusion().Grid<MvcSampleApplication.Model
s.Order>("FlatGrid")
.Datasource(Model)
.AllowKeyboardNavigation(true)
.EnablePaging()
.EnableSorting()
%>
View [cshtml]
@{
Html.Syncfusion().Syncfusion().Grid<MvcSampleApplication.Models.Order>(
"FlatGrid")
.Datasource(Model)
.AllowKeyboardNavigation(true)
.EnablePaging()
.EnableSorting()
.Render();
}
Controller
/// <summary>
/// Used for rendering the Grid initially.
/// </summary>
/// <returns>View page; it displays the grid.</returns>
public ActionResult Index()
{
6. In order to work with paging and sorting actions, create a Post method for Index
actions and bind the data source to the grid as shown in the code given below.
Controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
View [ASPX]
<%=Html.Syncfusion().Grid<MvcSampleApplication.Models.Student>("Keyboar
d_Grid",(GridPropertiesModel<MvcSampleApplication.Models.Student>)ViewD
ata.Model) %>
View [cshtml]
@(
Html.Syncfusion().Grid<MvcSampleApplication.Models.Student>("Keyboard_G
rid",(GridPropertiesModel<MvcSampleApplication.Models.Student>)ViewData
.Model))
4. Create a GridPropertiesModel in the Index method. Assign grid properties in this model
and pass the model from the controller to the view using the ViewData class as shown
below.
Controller
/// <summary>
/// Used for rendering the grid initially.
/// </summary>
/// <returns>View page; it displays the grid.</returns>
public ActionResult Index()
{
};
ViewData.Model = Keyboard_Grid;
return View(Data);
5. In order to work with paging and sorting actions, create a Post method for Index actions
and bind the data source to the grid as shown in the following code.
Controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index (PagingParams args)
{
Through GridBuilder
Through GridPropertiesModel
View [ASPX]
<%=Html.Syncfusion().Grid<MvcSampleApplication.Models.Order>("Fla
tGrid")
.Datasource(Model)
.AllowKeyboardNavigation(true)
.KeyConfigurator(key => {
key.ExportToExcel(Keys.AltPlusA);
key.FocusKey(Keys.CtrlPlusAltPlusA);
})
.EnablePaging()
.EnableSorting()
%>
View [cshtml]
@{
Html.Syncfusion().Grid<MvcSampleApplication.Models.Order>("FlatGrid")
.Datasource(Model)
.AllowKeyboardNavigation(true)
.KeyConfigurator(key => {
key.ExportToExcel(Keys.AltPlusA);
key.FocusKey(Keys.CtrlPlusAltPlusA);
})
.EnablePaging()
.EnableSorting()
.Render();
}
Controller
/// <summary>
/// Used for rendering the grid initially.
/// </summary>
/// <returns>View page; it displays the grid.</returns>
public ActionResult Index()
{
6. In order to work with paging and sorting actions, create a Post method for Index
actions and bind the data source to the grid as shown in the following code.
Controller
/// <summary>
/// Paging/sorting requests are mapped to this method. This
method invokes the
/// HtmlActionResult from the grid. The required response is
generated.
/// </summary>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
7. Run the application. Now FocusKey and ExportToExcel actions keyboard shortcuts
are configured.
View [ASPX]
<%=Html.Syncfusion().Grid<MvcSampleApplication.Models.Student>("Keyboar
d_Grid",(GridPropertiesModel<MvcSampleApplication.Models.Student>)ViewD
ata.Model) %>
View [cshtml]
@(
Html.Syncfusion().Grid<MvcSampleApplication.Models.Student>("Keyboard_G
rid",(GridPropertiesModel<MvcSampleApplication.Models.Student>)ViewData
.Model))
4. Create a GridPropertiesModel in the Index action. Assign grid properties in this model
and pass the model from the controller to the view using the ViewData class as shown in
the following code sample.
5. Configure the keys for all the actions using KeyConfigurator property. For example,
ExportToExcel and FocusKey actions are configured in the following code sample.
Controller
/// <summary>
/// Used for rendering the grid initially.
/// </summary>
/// <returns>View page; it displays the grid.</returns>
public ActionResult Index()
6. In order to work with paging and sorting actions, create a Post method for Index actions
and bind the data source to the grid as shown in the following code.
Controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index (PagingParams args)
{
IEnumerable data =new
StudentDataContext().AutoFormatStudent.Take(20);
return data.GridActions<Student>();
}
7. Run the application. Now FocusKey and ExportToExcel actions keyboard shortcuts are
configured.
Sample Link
To view the samples, follow the steps below:
1. Open the Grid sample browser from the dashboard (Refer to the Samples and Location
chapter).
2. Navigate to Grid.MVC > User Interaction > Keyboard Interface.
Keys.PgUp
Keys.PgDn
Keys.Insert
Keys.Delete
Keys.Enter
Keys.Esc
Keys.F2
Keys.CtrlPlusAltPlusF
Keys.AltPlusHome
Keys.AltPlusEnd
Keys.AltPlusPgUp
Keys.AltPlusPgDn
Keys.AltPlusInsert
Keys.AltPlusDelete
Keys.AltPlusEnter
Keys.AltPlusEsc
Keys.CtrlPlusAltPlusHome
Keys.CtrlPlusAltPlusEnd
Keys.CtrlPlusAltPlusPgUp
Keys.CtrlPlusAltPlusPgDn
Keys.CtrlPlusAltPlusInsert
Keys.CtrlPlusAltPlusDelete
Keys.CtrlPlusAltPlusEnter
Keys.CtrlPlusAltPlusEsc
Keys.AltPlusA
…
Keys.AltPlusZ
Keys.CtrlPlusAltPlusA
…
Keys.CtrlPlusAltPlusZ
Keys.AltPlusUpArrow
Keys.CtrlPlusAltPlusUpArrow
Keys.AltPlusDownArrow
Keys.CtrlPlusAltPlusDownArrow
Sample Link
To use the Keyboard Interface demo:
154. Select the Product Showcase option from the accordion on the left side of the sample
browser.
2. Select the Keyboard Interface demo.
The following figure gives you a basic idea of the structure and appearance of the context menu
in Essential Grid for MVC:
Item =
ContextMenuItems.AddRecord
HeaderCss = "addrecord"
0 Adds a new record to the grid.
TargetElement =
GridElements.Record
Text = "Add Record"
HeaderCss = "editrecord"
TargetElement =
GridElements.Record
Text = "Edit Record"
Item =
ContextMenuItems.DeleteRecord
HeaderCss = "deleterecord"
Deletes the current record in
2 TargetElement = the grid.
GridElements.Record
Text = "Delete Record"
Item = ContextMenuItems.Save
HeaderCss = "save"
Item = ContextMenuItems.Cancel
HeaderCss = "cancel"
Item =
ContextMenuItems.SortByAsc
HeaderCss = "sortbyasc"
Sorts the column in
5 TargetElement = ascending order.
GridElements.ColumnHeader
Text = "Sort By Ascending"
HeaderCss = "sortbydesc"
Sorts the column in
6 TargetElement = descending order.
GridElements.ColumnHeader
Text = "Sort By Descending"
Item =
ContextMenuItems.ClearSorting
HeaderCss = "clearsorting"
Clears the sorting from the
7 TargetElement = GridElements. column in the grid.
ColumnHeader
Text = "Clear Sorting"
Item = ContextMenuItems.GroupBy
HeaderCss = "groupby"
Item =
ContextMenuItems.ClearGrouping
HeaderCss = "cleargrouping"
Clears the grouping from the
9 TargetElement = GridElements. current column.
ColumnHeader
Text = "Clear Grouping"
Item = ContextMenuItems.Expand
HeaderCss = "expand"
HeaderCss = "collapse"
Collapses the current column
11 TargetElement = GridElements. in the grid.
GroupCaption
Text = "Collapse"
Item =
ContextMenuItems.ClearFilter
HeaderCss = "clearfilter"
Clears the filtering descriptors
12 TargetElement = GridElements. from the column.
ColumnHeader
Text = "Clear Filter"
Item =
ContextMenuItems.HideColumn
HeaderCss = "hidecolumn"
13 TargetElement = GridElements. Hides the current column.
ColumnHeader
Text = "Hide column"
Item =
ContextMenuItems.NextPage
HeaderCss = "nextpage"
Navigates to the next page of
14 TargetElement = GridElements. the grid.
Pager
Text = "Next Page"
Item =
ContextMenuItems.PreviousPage
Navigates to the previous
15 HeaderCss = "previouspage" page of the grid.
TargetElement = GridElements.
Pager
Item =
ContextMenuItems.LastPage
HeaderCss = "lastpage"
Navigates to the last page of
16 TargetElement = GridElements. the grid.
Pager
Text = "Last Page"
Item =
ContextMenuItems.FirstPage
HeaderCss = "firstpage"
Navigates to the first page of
17 TargetElement = GridElements. the grid.
Pager
Text = "First Page"
Item =
ContextMenuItems.NextPager
HeaderCss = "nextpager"
Navigates to the next pager of
18 TargetElement = GridElements. the grid.
Pager
Text = "Next Pager"
Item =
ContextMenuItems.PreviousPager
HeaderCss = "previouspager"
Navigates to the previous
19 TargetElement = GridElements. pager of the grid.
Pager
Text = "Previous Pager"
Item =
ContextMenuItems.RefreshPager It refreshes the pager of the
20
grid.
HeaderCss = "refreshpager"
Item =
ContextMenuItems.VisibleColumns
----
%>
View[cshtml]
@{
Html.Syncfusion().Grid<EditableOrder>("Grid")
.Datasource(Model)
.Column(column =>
{
column.Add(p => p.OrderID).HeaderText("Order
ID");
column.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
column.Add(p =>
p.CustomerID).HeaderText("Customer ID");
column.Add(p => p.ShipCountry).HeaderText("Ship
Country");
column.Add(p => p.OrderDate).HeaderText("Order
Date").Format("{OrderDate:MM/dd/yyyy}");
column.Add(p => p.Freight).HeaderText("Freight");
})
----
.EnableContextMenu() // Enabling the context menu.
----
.Render()
Controller
/// <summary>
/// Used for rendering the grid initially.
/// </summary>
/// <returns>View page; it displays the grid.</returns>
public ActionResult Index()
{
IEnumerable data = new
NorthwindDataContext().Orders.Take(200).ToList();
return View(data);
}
5. In order to work with filter actions, create a Post method for Index actions and bind the data
source to the grid as shown in the following code.
155.
Controller
<summary>
/// Paging/editing/filtering requests are mapped to this
method. This method invokes the HtmlActionResult
/// from the grid and the required response is generated.
/// </summary>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new
NorthwindDataContext().Orders.Take(200).ToList();
return data.GridActions<Order>();
6. Run the application. You can see the context menu as shown below in specified grid
elements.
View[ASPX]
View[cshtml]
{
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.CustomerID).HeaderText("Customer ID");
column.Add(p => p.ShipCountry).HeaderText("Ship Country");
column.Add(p => p.OrderDate).HeaderText("Order
Date").Format("{OrderDate:dd/MM/yyyy}");
column.Add(p => p.Freight).HeaderText("Price").Format("{0:c}");
}).Render();
)}
Controller
/// <summary>
/// Used for rendering the grid initially.
/// </summary>
/// <returns>View page; it displays the grid.</returns>
public ActionResult Index()
{
GridPropertiesModel<Order> gridModel = new
GridPropertiesModel<Order>()
{
DataSource = new
NorthwindDataContext().Orders.Take(200).ToList(),
Caption = "Orders",
EnableContextMenu = true,
-----
};
ViewData["GridModel"] = gridModel;
return View();
}
/// <summary>
/// Paging/editing/filtering requests are mapped to this
method. This method invokes the HtmlActionResult
/// from the grid and the required response is generated.
/// </summary>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new
NorthwindDataContext().Orders.Take(200).ToList();
return data.GridActions<Order>();
6. Run the application. You will be able to see the context menu as shown below:
1. Open the Grid sample browser from the dashboard (Refer to the Samples and Location
chapter).
2. Navigate to Grid.MVC > User Interaction > Context Menu
Type of Dependenc
Property Description Value it accepts
Property ies
Item Gets or sets ContextMenuIt ContextMenuItems.AddRecor NA
the ems d
ContextMenuIt
em
ContextMenuItems.EditReco
rd
ContextMenuItems.DeleteRe
cord
ContextMenuItems.Save
Type of Dependenc
Property Description Value it accepts
Property ies
ContextMenuItems.Cancel
ContextMenuItems.
SortByAsc
ContextMenuItems.SortByDe
sc
ContextMenuItems.ClearSor
ting
ContextMenuItems.GroupBy
ContextMenuItems.
ClearGrouping
ContextMenuItems.Expand
ContextMenuItems.Collapse
ContextMenuItems.ClearFil
ter
ContextMenuItems.HideColu
mn
ContextMenuItems.NextPage
ContextMenuItems.Previous
Page
ContextMenuItems.LastPage
ContextMenuItems.FirstPag
e
Type of Dependenc
Property Description Value it accepts
Property ies
ContextMenuItems.NextPage
r
ContextMenuItems.Previous
Pager
ContextMenuItems.RefreshP
ager
ContextMenuItems.VisibleC
olunms
4.15.2.2 Methods
Name Description Arguments
EnableContextMenu Enables the Context NA
Menu
View[ASPX]
<%=Html.Syncfusion().Grid<EditableOrder>("Grid")
.Datasource(Model)
.Column(column =>
{
column.Add(p => p.OrderID).HeaderText("Order
ID");
column.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
column.Add(p =>
p.CustomerID).HeaderText("Customer ID");
column.Add(p => p.ShipCountry).HeaderText("Ship
Country");
column.Add(p => p.OrderDate).HeaderText("Order
Date").Format("{OrderDate:MM/dd/yyyy}");
column.Add(p => p.Freight).HeaderText("Freight");
})
----
.EnableContextMenu() // Enabling the context menu.
.ContextMenuItems(items => {
})
----
%>
View[cshtml]
@{
Html.Syncfusion().Grid<EditableOrder>("Grid")
.Datasource(Model)
.Column(column =>
{
column.Add(p => p.OrderID).HeaderText("Order
ID");
column.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
column.Add(p =>
p.CustomerID).HeaderText("Customer ID");
column.Add(p => p.ShipCountry).HeaderText("Ship
Country");
column.Add(p => p.OrderDate).HeaderText("Order
Date").Format("{OrderDate:MM/dd/yyyy}");
column.Add(p => p.Freight).HeaderText("Freight");
})
----
.EnableContextMenu() // Enabling the context menu.
.ContextMenuItems(items => {
})
----
.Render()
View[ASPX]
<%=Html.Syncfusion().Grid<EditableOrder>("Grid")
.Datasource(Model)
.Column(column =>
{
column.Add(p => p.OrderID).HeaderText("Order
ID");
column.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
column.Add(p =>
p.CustomerID).HeaderText("Customer ID");
column.Add(p => p.ShipCountry).HeaderText("Ship
Country");
column.Add(p => p.OrderDate).HeaderText("Order
Date").Format("{OrderDate:MM/dd/yyyy}");
column.Add(p => p.Freight).HeaderText("Freight");
})
----
.EnableContextMenu() // Enabling the context menu.
.ContextMenuItems(items => {
----
%>
View[cshtml]
@{
Html.Syncfusion().Grid<EditableOrder>("Grid")
.Datasource(Model)
.Column(column =>
{
column.Add(p => p.OrderID).HeaderText("Order
ID");
column.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
column.Add(p =>
p.CustomerID).HeaderText("Customer ID");
column.Add(p => p.ShipCountry).HeaderText("Ship
Country");
column.Add(p => p.OrderDate).HeaderText("Order
Date").Format("{OrderDate:MM/dd/yyyy}");
column.Add(p => p.Freight).HeaderText("Freight");
})
----
.EnableContextMenu() // Enabling the context menu.
.ContextMenuItems(items => {
items.RemoveMatchedItems(it => it.Item ==
ContextMenuItems.RefreshPager); // Removed Refresh Pager context menu
item.
})
----
.Render()
6. You can also clear all the context menu items using the Clear method in the
ContextMenuItems builder as shown in the code samples below.
View[ASPX]
<%=Html.Syncfusion().Grid<EditableOrder>("Grid")
.Datasource(Model)
.Column(column =>
{
column.Add(p => p.OrderID).HeaderText("Order
ID");
column.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
column.Add(p =>
p.CustomerID).HeaderText("Customer ID");
column.Add(p => p.ShipCountry).HeaderText("Ship
Country");
----
%>
View[cshtml]
@{
Html.Syncfusion().Grid<EditableOrder>("Grid")
.Datasource(Model)
.Column(column =>
{
column.Add(p => p.OrderID).HeaderText("Order
ID");
column.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
column.Add(p =>
p.CustomerID).HeaderText("Customer ID");
column.Add(p => p.ShipCountry).HeaderText("Ship
Country");
column.Add(p => p.OrderDate).HeaderText("Order
Date").Format("{OrderDate:MM/dd/yyyy}");
column.Add(p => p.Freight).HeaderText("Freight");
})
----
.EnableContextMenu() // Enabling the context menu.
.ContextMenuItems(items => {
items.Clear() // Cleared all built-in items.
})
----
.Render()
Controller
/// <summary>
/// Used for rendering the grid initially.
/// </summary>
/// <returns>View page; it displays the grid.</returns>
public ActionResult Index()
{
IEnumerable data = new
NorthwindDataContext().Orders.Take(200).ToList();
return View(data);
}
8. In order to work with filter actions, create a Post method for Index actions and bind the data
source to the grid as shown in the following code.
Controller
<summary>
/// Paging/editing/filtering requests are mapped to this
method. This method invokes the HtmlActionResult
/// from the grid and the required response is generated.
/// </summary>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new
NorthwindDataContext().Orders.Take(200).ToList();
return data.GridActions<Order>();
View[ASPX]
View[cshtml]
Date").Format("{OrderDate:dd/MM/yyyy}");
column.Add(p => p.Freight).HeaderText("Price").Format("{0:c}");
}).Render();
)}
Controller
/// <summary>
/// Used for rendering the grid initially.
/// </summary>
/// <returns>View page; it displays the grid.</returns>
public ActionResult Index()
{
GridPropertiesModel<Order> gridModel = new
GridPropertiesModel<Order>()
{
DataSource = new
NorthwindDataContext().Orders.Take(200).ToList(),
Caption = "Orders",
EnableContextMenu = true,
-----
};
ViewData["GridModel"] = gridModel;
return View();
}
/// <summary>
/// Paging/editing/filtering requests are mapped to this
method. This method invokes the HtmlActionResult
/// from the grid and the required response is generated.
/// </summary>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new
NorthwindDataContext().Orders.Take(200).ToList();
return data.GridActions<Order>();
156.
Controller
/// <summary>
/// Used for rendering the grid initially.
/// </summary>
/// <returns>View page; it displays the grid.</returns>
public ActionResult Index()
{
GridPropertiesModel<Order> gridModel = new
GridPropertiesModel<Order>()
{
DataSource = new
NorthwindDataContext().Orders.Take(200).ToList(),
Caption = "Orders",
EnableContextMenu = true,
-----
};
gridModel.ContextMenuItems.Add(new ContextMenuItem() { Item =
ContextMenuItems.Custom, HeaderCss = "PDFExport", TargetElement =
GridElements.All, Text = "Export to PDF" });
gridModel.ContextMenuItems.Add(new ContextMenuItem() { Item
= ContextMenuItems.Custom, HeaderCss = "WordExport", TargetElement =
GridElements.Record, Text = "Export to Word" });
gridModel.ContextMenuItems.Add(new ContextMenuItem() { Item
= ContextMenuItems.Custom, HeaderCss = "ExcelExport", TargetElement =
GridElements.Record, Text = "Export to Excel" });
ViewData["GridModel"] = gridModel;
return View();
}
7. To remove custom menu items, remove all methods providing predicates as the argument
as shown in the code below:
Controller
/// <summary>
/// Used for rendering the grid initially.
/// </summary>
/// <returns>View page; it displays the grid.</returns>
public ActionResult Index()
{
GridPropertiesModel<Order> gridModel = new
GridPropertiesModel<Order>()
{
DataSource = new
NorthwindDataContext().Orders.Take(200).ToList(),
Caption = "Orders",
EnableContextMenu = true,
-----
};
gridModel.ContextMenuItems.RemoveAll(c => c.Item ==
ContextMenuItems.AddRecord);
ViewData["GridModel"] = gridModel;
return View();
}
8. To clear the custom items in the Context menu, clear methods in the Context menu list as
shown in the code samples below:
157.
Controller
/// <summary>
/// Used for rendering the grid initially.
/// </summary>
/// <returns>View page, it displays the grid.</returns>
public ActionResult Index()
{
GridPropertiesModel<Order> gridModel = new
GridPropertiesModel<Order>()
{
DataSource = new
NorthwindDataContext().Orders.Take(200).ToList(),
Caption = "Orders",
EnableContextMenu = true,
-----
};
gridModel.ContextMenuItems.Clear();
ViewData["GridModel"] = gridModel;
return View();
}
9. Run the application. You will be able to see the context menu as shown below:
4.16 Appearance
4.16.1 Built-in Skin Styles
The Grid control has some predefined skins which can be controlled through a single property
setting.
Properties
Skins.Blend
Skins.Blueberry
Skins.Marble
Skins.Metro
Skins.Midnight
Skins.Monochrome
Skins.Olive
Skins.Sandune
Skins.Turquoise
Skins.VS2010
Methods
<%=Html.Syncfusion().Grid<Order>("OrdersGrid")
.Datasource(Model)
.Caption("Orders")
.Column(column =>
{
column.Add(p =>
p.CustomerID).HeaderText("Customer ID");
column.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
column.Add(p =>
p.OrderID).HeaderText("Order ID");
column.Add(P =>
P.ShipCountry).HeaderText("Ship Country");
column.Add(p =>
p.ShipCity).HeaderText("Ship City");
})
.EnablePaging()
.EnableSorting()
%>
160.
View [cshtml]
@{ Html.Syncfusion().Grid<Order>("OrdersGrid")
.Datasource(Model)
.Caption("Orders")
.Column(column =>
{
column.Add(p =>
p.CustomerID).HeaderText("Customer ID");
column.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
column.Add(p =>
p.OrderID).HeaderText("Order ID");
column.Add(P =>
P.ShipCountry).HeaderText("Ship Country");
column.Add(p =>
p.ShipCity).HeaderText("Ship City");
})
.EnablePaging()
.EnableSorting()
.Render();
}
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("OrdersGrid")
.Datasource(Model)
.Caption("Orders")
………
………
.AutoFormat(Skins.Almond)
%>
View [cshtml]
@{ Html.Syncfusion().Grid<Order>("OrdersGrid")
.Datasource(Model)
.Caption("Orders")
………
………
.AutoFormat(Skins.Almond)
.Render();
}
1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. Add the following code in the Index.aspx file to create the Grid control in the view.
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("Orders_Grid","GridModel", column=> {
column.Add(p =>
p.CustomerID).HeaderText("Customer ID");
column.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
column.Add(p => p.OrderID).HeaderText("Order
ID");
column.Add(P => P.ShipCountry).HeaderText("Ship
Country");
column.Add(p => p.ShipCity).HeaderText("Ship
City");
})%>
View [cshtml]
@( Html.Syncfusion().Grid<Order>("Orders_Grid","GridModel",
column=> {
column.Add(p =>
p.CustomerID).HeaderText("Customer ID");
column.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
column.Add(p => p.OrderID).HeaderText("Order
ID");
column.Add(P => P.ShipCountry).HeaderText("Ship
Country");
column.Add(p => p.ShipCity).HeaderText("Ship
City");
}))
4. Specify the skin name using the AutoFormat property and pass the model to the view
using the ViewData() method.
Controller
NorthwindDataContext().Orders.Take(500),
Caption = "Orders",
AllowPaging = true,
AllowSorting = true,
AutoFormat = Skins.Almond
};
ViewData["GridModel"] = model;
Properties
Methods
In order to work with this feature please follow the steps below:
1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. In the view create the Grid control and configure its properties.
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("OrdersGrid")
.Datasource(Model)
.Caption("Orders")
.Column(column =>
{
column.Add(p => p.CustomerID).HeaderText("Customer
ID").Width(100);
column.Add(p => p.EmployeeID).HeaderText("Employee
ID").TextAlign(TextAlignment.Right).Width(100);
column.Add(p => p.OrderID).HeaderText("Order
ID").TextAlign(TextAlignment.Right).Width(90);
column.Add(P => P.ShipCountry).HeaderText("Ship
Country").Width(110);
column.Add(p => p.ShipName).HeaderText("Ship Name");
column.Add(p => p.OrderDate).HeaderText("Order
Date").Format("{OrderDate:MM/dd/yyyy}").Width(120);
}) .EnableSorting()
.EnablePaging()
.EnableLegacySettings(true)
.CustomCss("Syncfusion-Grid-Greenish")
%>
162.
View [cshtml]
@{ Html.Syncfusion().Grid<Order>("OrdersGrid")
.Datasource(Model)
.Caption("Orders")
.Column(column =>
{
column.Add(p => p.CustomerID).HeaderText("Customer
ID").Width(100);
column.Add(p => p.EmployeeID).HeaderText("Employee
ID").TextAlign(TextAlignment.Right).Width(100);
column.Add(p => p.OrderID).HeaderText("Order
ID").TextAlign(TextAlignment.Right).Width(90);
column.Add(P => P.ShipCountry).HeaderText("Ship
Country").Width(110);
column.Add(p => p.ShipName).HeaderText("Ship Name");
column.Add(p => p.OrderDate).HeaderText("Order
Date").Format("{OrderDate:MM/dd/yyyy}").Width(120);
}) .EnableSorting()
.EnablePaging()
.EnableLegacySettings(true)
.Render();
}
4. Open the grid online sample browser by using the below link
163. Online sample Link: http://mvc.syncfusion.com/demos/ui/grid
Figure 217: Click the Gallery button the Basic themes are loaded
8. Apply your css in the left hand side accordion and see the changes in the grid.
9. In this case, we have customized the grid and download the css and sprite images for
the “Greenish” skin using the download button which is in the right corner of the theme
studio.
10. Enter the skin name “Greenish” in the Skin Name text box.
11. Select Grid checkbox and click Download Zip button.
166.
Note: If you want the css of the sub controls of the grid then check the Tools check box also.
167. Download Zip File:
http://www.syncfusion.com/Downloads/Support/Online%20Document%20Uploads/ASP
NET-MVC/sfThemes.zip
168.
12. Add the new custom CSS and sprite image in the application and add this custom CSS
in the master page as demonstrated below:
[Site.Master]
<head runat="server">
<title><asp:ContentPlaceHolder ID="TitleContent"
runat="server" /></title>
<link href="<%=
Url.Content("~/Content/CustomCss/Syncfusion-Grid-Greenish.css")%>"
rel="stylesheet"
type="text/css" />
……………
……………
</head>
[_Layout.cshtml]
<head runat="server">
<title><asp:ContentPlaceHolder ID="TitleContent"
runat="server" /></title>
<link href="@Url.Content("~/Content/CustomCss/Syncfusion-
Grid-Greenish.css")" rel="stylesheet" type="text/css" />
……………
……………
</head>
13. Specify the custom CSS class name using the CustomCss() method. In this case
“Syncfusion-Grid-Greenish” is the custom CSS class name.
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("OrdersGrid")
.Datasource(Model)
.Caption("Orders")
.Column(.Column(column =>
{
column.Add(p => p.CustomerID).HeaderText("Customer
ID").Width(100);
column.Add(p => p.EmployeeID).HeaderText("Employee
ID").TextAlign(TextAlignment.Right).Width(100);
column.Add(p => p.OrderID).HeaderText("Order
ID").TextAlign(TextAlignment.Right).Width(90);
column.Add(P => P.ShipCountry).HeaderText("Ship
Country").Width(110);
column.Add(p => p.ShipName).HeaderText("Ship Name");
column.Add(p => p.OrderDate).HeaderText("Order
Date").Format("{OrderDate:MM/dd/yyyy}").Width(120);
}) .EnableSorting()
.EnablePaging()
.EnableLegacySettings(true)
.CustomCss("Syncfusion-Grid-Greenish")
%>
View [cshtml]
@{ Html.Syncfusion().Grid<Order>("OrdersGrid")
.Datasource(Model)
.Caption("Orders")
.Column(.Column(column =>
{
column.Add(p => p.CustomerID).HeaderText("Customer
ID").Width(100);
column.Add(p => p.EmployeeID).HeaderText("Employee
ID").TextAlign(TextAlignment.Right).Width(100);
column.Add(p => p.OrderID).HeaderText("Order
ID").TextAlign(TextAlignment.Right).Width(90);
column.Add(P => P.ShipCountry).HeaderText("Ship
Country").Width(110);
column.Add(p => p.ShipName).HeaderText("Ship Name");
column.Add(p => p.OrderDate).HeaderText("Order
Date").Format("{OrderDate:MM/dd/yyyy}").Width(120);
}) .EnableSorting()
.EnablePaging()
.EnableLegacySettings(true)
.CustomCss("Syncfusion-Grid-Greenish")
.Render();
}
14. Run the application. The grid will appear as shown below.
View [ASPX]
<%=Html.Syncfusion().Grid<MVCSampleBrowser.Models.Order>(
"CustomCSS_Grid", "GridModel",
column =>
{
column.Add(p => p.CustomerID).HeaderText("Customer
ID").Width(100);
View [cshtml]
@(Html.Syncfusion().Grid<MVCSampleBrowser.Models.Order>(
"CustomCSS_Grid", "GridModel",
column =>
{
column.Add(p => p.CustomerID).HeaderText("Customer
ID").Width(100);
column.Add(p => p.EmployeeID).HeaderText("Employee
ID").TextAlign(TextAlignment.Right).Width(100);
column.Add(p => p.OrderID).HeaderText("Order
ID").TextAlign(TextAlignment.Right).Width(90);
column.Add(P => P.ShipCountry).HeaderText("Ship
Country").Width(110);
column.Add(p => p.ShipName).HeaderText("Ship Name");
column.Add(p => p.OrderDate).HeaderText("Order
Date").Format("{OrderDate:MM/dd/yyyy}").Width(120);
}))
Controller
5. Open the grid online sample browser by using the below link
169. Online sample Link: http://mvc.syncfusion.com/demos/ui/grid
Figure 223: Click the Gallery button the Basic themes are loaded
174.
8. Select the Almond skin from the Basic Themes tab.
175.
9. Apply your CSS in the left hand side accordion and see the changes in the grid.
10. In this case, we have customized the grid and download the css and sprite images for
the “Greenish” skin using the download button which is in the right corner of the theme
studio.
Note: If you want the css of the sub controls of the grid then check the Tools check box also.
177. Download Zip File:
http://www.syncfusion.com/Downloads/Support/Online%20Document%20Uploads/ASP
NET-MVC/sfThemes.zip
178.
13. Add the new custom CSS and sprite image to the application and add this custom CSS
in the master page as shown below:
[Site.Master]
<head runat="server">
<title><asp:ContentPlaceHolder ID="TitleContent"
runat="server" /></title>
<link href="<%=
Url.Content("~/Content/CustomCss/Syncfusion-Grid-Greenish.css")%>"
rel="stylesheet" type="text/css" />
……………
……………
</head>
[_Layout.cshtml]
<head runat="server">
<title><asp:ContentPlaceHolder ID="TitleContent"
runat="server" /></title>
<link href="@Url.Content("~/Content/CustomCss/Syncfusion-
Grid-Greenish.css")" rel="stylesheet" type="text/css" />
……………
……………
</head>
14. Specify the custom CSS class name using the CustomCss property and pass the
model to the view using the ViewData() method.
Controller
15. Run the application. The grid will appear as shown below.
4.17 Localization
Localization is the process of customizing the user interface (UI) as locale-specific in order to
display regional data i.e. in a language and culture specific to a particular country or region. This
is done with the help of localized resources by the control. Essential Grid provides inherent
support to localize its UI.
1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. Create a folder named App_GlobalResources in the application and create your own
localization resource (.resx) file in this folder.
In order to create a new localization resource file, download the default localization file from the
following location, rename it, and then use Visual Studio to edit the values.
GridResource.zip
Note: The name of the localization file should be in the format GridResource.[culture].resx. For
example: "GridLocalization.fr-FR.resx"
4. Create the Grid control in the view and configure its properties.
179. There are two ways to specify the culture information, namely:
Setting the CurrentUICulture property of the CurrentThread inside your Action method:
[Controller]
public ActionResult Index()
{
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.EnablePaging()
.EnableSorting()
.EnableFiltering()
.AutoFormat(Skins.Sandune)
.Localize("fr-FR")// Specify the culture code.
.Column( columns => {
columns.Add(p => p.OrderID).HeaderText("Order ID");
columns.Add(p => p.CustomerID).HeaderText("Customer ID");
columns.Add(p => p.EmployeeID).HeaderText("Employee ID");
View [cshtml]
@{ Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.EnablePaging()
.EnableSorting()
.EnableFiltering()
.AutoFormat(Skins.Sandune)
.Localize("fr-FR")// Specify the culture code.
.Column( columns => {
columns.Add(p => p.OrderID).HeaderText("Order ID");
[Controller]
/// <summary>
/// Used for rendering the grid initially.
/// </summary>
/// <returns>View page; it displays the grid.</returns>
public ActionResult Index()
{
var data = new NorthwindDataContext().Orders;
return View(data);
}
<%=Html.Syncfusion().ScriptManager().EnableGlobalization().Render();%>
</body>
[_Layout.cshtml]
<body>
......
......
@{Html.Syncfusion().ScriptManager().EnableGlobalization().Render();}
</body>
4.17.1.1.1 Customization
If you want to customize the localization resource file folder path, then use the
LocalizationPath() method.
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.Localize("fr-FR")// Specify the culture code.
.LocalizationPath("~/App_LocalResources") // Specify the folder.
%>
View [cshtml]
@{ Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.Localize("fr-FR")// Specify the culture code.
In order to create a new localization resource file, download the default localization file from the
following location, rename it, and then use Visual Studio to edit the values.
GridResource.zip
Note: The name of the localization file should be in the format GridResource.[culture].resx. For
example: "GridLocalization.fr-FR.resx"
4. Add the following code in the Index.aspx file to create the Grid control in the view.
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("Grid1","GridModel", column
s => {
columns.Add(p => p.OrderID).HeaderText("Order ID");
columns.Add(p => p.CustomerID).HeaderText("Customer ID");
columns.Add(p => p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship Country");
columns.Add(p => p.OrderDate).HeaderText("Order Date");
})%>
View [cshtml]
@( Html.Syncfusion().Grid<Order>("Grid1","GridModel", columns => {
columns.Add(p => p.OrderID).HeaderText("Order ID");
columns.Add(p => p.CustomerID).HeaderText("Customer ID");
columns.Add(p => p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship Country");
columns.Add(p => p.OrderDate).HeaderText("Order Date");
}))
Setting the CurrentUICulture property of the CurrentThread inside your Action method.
[Controller]
public ActionResult Index()
{
[Controller]
public ActionResult Index()
{
GridPropertiesModel<Order> gridModel = new GridPropertiesModel<Or
der>()
{
DataSource = new NorthwindDataContext().Orders,
Caption = "Orders",
AllowPaging = true,
AllowFiltering = true,
AutoFormat = Skins.Sandune,
Localize="fr-FR" // specify Culture code
};
ViewData["GridModel"] = gridModel;
return View();
}
[Site.Master]
<body>
......
......
<%=Html.Syncfusion().ScriptManager().EnableGlobalization().Render();%>
</body>
[_Layout.cshtml]
<body>
......
......
@{Html.Syncfusion().ScriptManager().EnableGlobalization().Render();}
</body>
7. Run the application. The grid will appear as shown in the following screenshot:
4.17.1.2.1 Customization
If you want to customize the localization resource files folder path use the LocalizationPath
property.
[Controller]
public ActionResult Index()
{
GridPropertiesModel<Order> gridModel = new GridPropertiesModel<Or
der>()
{
DataSource = new NorthwindDataContext().Orders,
Caption = "Orders",
AllowPaging = true,
AllowFiltering = true,
AutoFormat = Skins.Sandune,
Localize="fr-FR", // Specify culture code.
LocalizationPath="~/App_LocalResources"//
Specify the folder path.
};
ViewData["GridModel"] = gridModel;
return View();
}
LocalizationPath Get or set the Server side Any string value. Localize
localization
Default:
resource path of
“~/App_GlobalRe
the resource file
sources”
location
Methods
Sample Link
To view the samples, follow the steps below:
1. Open the Grid sample browser from the dashboard (Refer to the Samples and Location
chapter).
2. Navigate to Grid.MVC > Localization > Localization
.AutoFormat(Skins.Almond)
.ChildGrid(child =>
{
// Append the foreign key related to the parent
grid as a unique ID for the child grid.
child.ChildGridTemplate(Html.Syncfusion().Grid<Order_Detail>("ChildGrid
_${OrderID}")
.Caption("OrderDetails Grid")
.Mappers(map =>
{
// Specify the foreign key related to the parent
grid.
// Separate action method for the child grid.
map.Action("ChildGrid", new { OrderID =
"${OrderID}" });
})
.ToChildGridTemplate());
})
%>
View[cshtml]
@{
Html.Syncfusion().Grid<Order>("GridSrc")
.Datasource(Model)
.Caption("Order Grid")
.AutoFormat(Skins.Almond)
.ChildGrid(child =>
{
// Append the foreign key related to the parent
grid as a unique ID for the child grid.
child.ChildGridTemplate(Html.Syncfusion().Grid<
Order_Detail>("ChildGrid_${OrderID}")
.Caption("OrderDetails Grid")
.Mappers(map =>
{
// Specify the foreign key related to the
parent grid.
// Separate action method for the child grid.
map.Action("ChildGrid", new { OrderID =
"${OrderID}" });
})
.ToChildGridTemplate());
})
.Render();
}
[Controller]
9. In order to work with paging actions, create a post method for the index action and bind
the data source to the grid as shown in the following code:
[Controller]
/// <summary>
/// Paging action mapper, Paging Request is mapped here
/// </summary>
/// <param name="args">Contains Paging Information.</param>
/// <returns>HtmlActionResult which returns data displayed on
the Grid</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new NorthwindDataContext
().Orders.Take(60).ToList();
return data.GridActions<Order>();
}
10. In order to work with the child grid, create a post method for the child grid and bind the
data source to the child grid as shown in the following code:
[Controller]
[AcceptVerbs(HttpVerbs.Post)]
11. Run the application. The grid will appear as shown below:
Perform the following steps to create a hierarchical grid through GridBuilder in JSON mode:
1.Create a model in the application (refer to How to > Adding model to the application).
2.Create the Grid control in the view and configure the properties.
3.Use the ChildGrid method as shown below.
4.The Mappers Action method for the child grid should contain the Foreign Key to relate
to the Parent.
5. It should end with the method ToChildGridTemplate.
View[ASPX]
<%=Html.Syncfusion().Grid<EmployeeView>("GridSrc")
.Caption("Employee Grid")
.AutoFormat(Skins.Almond)
.ActionMode(ActionMode.JSON)
.ChildGrid(child =>
{
// Append the foreign key related to the parent grid
as a unique ID for the child grid.
grid.child.ChildGridTemplate(Html.Syncfusion().Grid<OrdersView>("ChildG
rid_${EmployeeID}")
.Mappers(map =>
{
// Specify the foreign key related to the parent
grid.
// Separate action method for the child grid.
map.Action("JSONChildGrid", new {
EmployeeID = "${ EmployeeID}" });
})
.ToChildGridTemplate());
})
%>
View[cshtml]
@{
Html.Syncfusion().Grid<EmployeeView>("GridSrc")
.Datasource(Model)
.Caption("Employee Grid")
.AutoFormat(Skins.Almond)
.ActionMode(ActionMode.JSON)
.ChildGrid(child =>
{
child.ChildGridTemplate(Html.Syncfusion().Grid<OrdersView>("ChildGrid_$
{EmployeeID}").
.Mappers(map =>
{
// Specify the foreign key related to the parent
grid.
// Separate action method for the child grid.
map.Action("JSONChildGrid", new {
EmployeeID = "${ EmployeeID}" });
})
.ToChildGridTemplate());
})
.Render(); }
[Controller]
public ActionResult Index()
{
return View();
8. In order to work with paging actions, create a post method for the index action and bind
the data source to the grid as given in the following code sample.
[Controller]
/// <summary>
/// Used to bind the grid.
/// </summary>
/// <returns>View page displays the grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
var ordersData = new
NorthwindDataContext().EmployeeViews.ToList();
return ordersData.GridJSONActions<EmployeeView>();
}
9. In order to work with the child grid, create a post method for the child grid and bind the
data source to the child grid as shown in the following code:
[Controller]
/// <summary>
/// Used to bind the child grid.
/// </summary>
/// <returns>View page displays the grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult JSONChildGrid(PagingParams args, string
EmployeeID)
{
IEnumerable data = new
NorthwindDataContext().OrdersViews.Where(c => c.EmployeeID ==
EmployeeID).ToList();
return data.GridJSONActions<OrdersView>();
}
10. Run the application. The grid will appear as shown below:
Properties
Methods
Method Description Parameters Type Return Reference
Type links
Sets the child
ChildGrid grid if the
String IGridBuilder NA
hierarchical
grid is needed.
ChildGridTem
plate (to
Renders the render the
ToChildGridTe ChildGridTem
grid in child child grid, the
mplate plate NA
grid template user has to
format. render the grid
as this type).
Events
Event Description Arguments Type Reference links
Using the OnRecordCollapsing event, users can avoid a collapse event. Using the
OnRecordExpanding event, users can avoid an expand event.
The client-side events are used in ASPX as shown below in server mode through GridBuilder.
View[ASPX]
<%=Html.Syncfusion().Grid<Order>("GridSrc")
.Datasource(Model)
.Caption("Order Grid")
.AutoFormat(Skins.Almond)
.ClientSideEvents(eve =>
{
eve.OnRecordCollapsing("OnRecordCollapsing");
eve.OnRecordExpanding("OnRecordExpanding");
eve.OnRecordCollapsed("OnRecordCollapsed");
eve.OnRecordExpanded("OnRecordExpanded");
})
.ChildGrid(child =>
{
child.ChildGridTemplate(Html.Syncfusion().Grid<Order_Detail>("ChildGrid
_${OrderID}")
.Caption("OrderDetails Grid")
.Mappers(map =>
{
// Specify the foreign key related to the parent
grid.
// Separate action method for the child grid.
map.Action("ChildGrid", new { OrderID =
"${OrderID}" });
})
.ToChildGridTemplate());
})
%>
For Razor, use the code shown below in server mode through GridBuilder.
View[cshtml]
@{
Html.Syncfusion().Grid<Order>("GridSrc")
.Datasource(Model)
.Caption("Order Grid")
.AutoFormat(Skins.Almond)
.ClientSideEvents(eve =>
{
eve.OnRecordCollapsing("OnRecordCollapsing");
eve.OnRecordExpanding("OnRecordExpanding");
eve.OnRecordCollapsed("OnRecordCollapsed");
eve.OnRecordExpanded("OnRecordExpanded");
})
.ChildGrid(child =>
{
child.ChildGridTemplate(Html.Syncfusion().Grid<
Order_Detail>("ChildGrid_${OrderID}")
.Caption("OrderDetails Grid")
.Mappers(map =>
{
// Specify the foreign key related to the parent
grid.
// Separate action method for the child grid.
map.Action("ChildGrid", new { OrderID =
"${OrderID}" });
})
.ToChildGridTemplate());
})
.Render();
}
[Javascript]
<script type="text/javascript">
function OnRecordCollapsing(sender, args) {
// perform any action during the record is collapsing.
}
Appearance
4.18.3 Editing
4.18.3.1 Server Mode
1. Create a model in the application (refer to How to > Adding model to the application).
2. Create a strongly typed view (refer to How to > strongly typed view).
3. Create the Grid control in the view and configure their properties.
4. Use the ChildGrid method as shown below.
5. The Mappers Action method for the child grid should contain the Foreign Key to relate to
the Parent.
6. It should end with the method ToChildGridTemplate.
View[ASPX]
<%=Html.Syncfusion().Grid<EditableOrder>("GridSrc")
.Datasource(Model)
.Caption("Order Grid")
.AutoFormat(Skins.Almond)
.ChildGrid(child =>
{
// Append the foreign key related to the parent
grid as a unique ID for the child grid.
child.ChildGridTemplate(Html.Syncfusion().Grid<OrderDetailEdit>("ChildG
rid_${OrderID}")
.Caption("OrderDetails Grid")
.Mappers(map =>
{
// Specify the foreign key related to the parent
grid.
// Separate action method for the child grid.
map.Action("ChildGrid", new { OrderID =
"${OrderID}" });
})
.ToChildGridTemplate());
})
%>
@{
Html.Syncfusion().Grid<EditableOrder>("GridSrc")
.Datasource(Model)
.Caption("Order Grid")
.AutoFormat(Skins.Almond)
.ChildGrid(child =>
{
// Append the foreign key related to the parent
grid as a unique ID for the child grid.
child.ChildGridTemplate(Html.Syncfusion().Grid<OrderDetailEdit>("ChildG
rid_${OrderID}")
.Caption("OrderDetails Grid")
.Mappers(map =>
{
// Specify the foreign key related to the
parent grid.
// Separate action method for the child grid.
map.Action("ChildGrid", new { OrderID =
"${OrderID}" });
})
.ToChildGridTemplate());
})
.Render();
}
8. Enable editing by using the Editing method and configure the editing properties such as
AllowNew, AllowEdit, and AllowDelete, as displayed below.
View [ASPX]
<%=Html.Syncfusion().Grid<EditableOrder>("GridSrc")
.Datasource(Model)
.Caption("Order Grid")
.AutoFormat(Skins.Almond)
.ChildGrid(child =>
{
// Append the foreign key related to the parent
grid as a unique ID for the child grid.
child.ChildGridTemplate(Html.Syncfusion().Grid<OrderDetailEdit>("ChildG
rid_${OrderID}")
.Caption("OrderDetails Grid")
.Editing( edit=>{
edit.AllowEdit(true, "Home/ChildOrderSave")// Specify
the action method that will perform the update action.
.AllowNew(true, "Home/ChildAddOrder")// Specify the
action method that will perform the insert action.
.AllowDelete(true, "Home/ChildDeleteOrder");//
Specify the action method that will perform the delete
action.
})
.ToChildGridTemplate());
})
%>
View [cshtml]
@{
Html.Syncfusion().Grid<EditableOrder>("GridSrc")
.Datasource(Model)
.Caption("Order Grid")
.AutoFormat(Skins.Almond)
.ChildGrid(child =>
{
// Append the foreign key related to the parent
grid as a unique ID for the child grid.
child.ChildGridTemplate(Html.Syncfusion().Grid<OrderDetailEdit>("ChildG
rid_${OrderID}")
.Caption("OrderDetails Grid")
.Caption("Orders")
.Editing( edit=>{
edit.AllowEdit(true, "Home/ChildOrderSave")// Specify
the action method that will perform the update action.
.AllowNew(true, "Home/ChildAddOrder")// Specify the
action method that will perform the insert action.
.AllowDelete(true, "Home/ChildDeleteOrder");//
Specify the action method that will perform the delete action.
})
.ToChildGridTemplate());
})
.Render();
}
9. The Grid control allows users to add new records through grid toolbar items. In this
example, the AddNew, Edit, Delete, Save, and Cancel buttons have been added as
toolbar items in the following code example:
View [ASPX]
<%=Html.Syncfusion().Grid<EditableOrder>("GridSrc")
.Datasource(Model)
.Caption("Order Grid")
.AutoFormat(Skins.Almond)
.ChildGrid(child =>
{
// Append the foreign key related to the parent
grid as a unique ID for the child grid.
child.ChildGridTemplate(Html.Syncfusion().Grid<OrderDetailEdit>("ChildG
rid_${OrderID}")
.Caption("OrderDetails Grid")
.ToolBar(tools =>
{
tools.Add(GridToolBarItems.AddNew)// Toolbar
item for inserting a record.
.Add(GridToolBarItems.Edit)// Toolbar
item for editing a record.
.Add(GridToolBarItems.Delete)// Toolbar
item for deleting a record.
.Add(GridToolBarItems.Update)// Toolbar
item for saving changes.
.Add(GridToolBarItems.Cancel);// Toolbar
item for canceling a
request.
})
.ToChildGridTemplate());
})
%>
View [cshtml]
@{
Html.Syncfusion().Grid<EditableOrder>("GridSrc")
.Datasource(Model)
.Caption("Order Grid")
.AutoFormat(Skins.Almond)
.ChildGrid(child =>
{
// Append the foreign key related to the parent
grid as a unique ID for the child grid.
child.ChildGridTemplate(Html.Syncfusion().Grid<OrderDetailEdit>("ChildG
rid_${OrderID}")
.Caption("OrderDetails Grid")
.Caption("Orders")
.ToolBar(tools =>
{
tools.Add(GridToolBarItems.AddNew)// Toolbar
item for inserting a record.
.Add(GridToolBarItems.Edit)// Toolbar
item for editing a record.
.Add(GridToolBarItems.Delete)// Toolbar
item for deleting a record.
.Add(GridToolBarItems.Update)// Toolbar
item for saving changes.
.Add(GridToolBarItems.Cancel);// Toolbar
item for canceling a
request.
})
.ToChildGridTemplate());
})
.Render();
}
10. Specify the Primary property that uniquely identifies the grid record.
View [ASPX]
<%=Html.Syncfusion().Grid<EditableOrder>("GridSrc")
.Datasource(Model)
.Caption("Order Grid")
.AutoFormat(Skins.Almond)
.ChildGrid(child =>
{
// Append the foreign key related to the parent
grid as a unique ID for the child grid.
child.ChildGridTemplate(Html.Syncfusion().Grid<OrderDetailEdit>("ChildG
rid_${OrderID}")
.Caption("OrderDetails Grid")
.Editing( edit=>{
edit.PrimaryKey(key => key.Add(p =>
p.OrderID)); // Add primary key to primary key collections.
}) .ToChildGridTemplate());
})
%>
View [cshtml]
@{ Html.Syncfusion().Grid<EditableOrder>("GridSrc")
.Datasource(Model)
.Caption("Order Grid")
.AutoFormat(Skins.Almond)
.ChildGrid(child =>
{
// Append the foreign key related to the parent
grid as a unique ID for the child grid.
child.ChildGridTemplate(Html.Syncfusion().Grid<OrderDetailEdit>("ChildG
rid_${OrderID}")
.Caption("OrderDetails Grid")
.Editing( edit=>{
edit.PrimaryKey(key => key.Add(p =>
p.OrderID)); // Add primary key to primary key collections.
}) .ToChildGridTemplate());
}) .Render();
}
11. Specify the grid editing mode through the EditMode() method.
View [ASPX]
<%=Html.Syncfusion().Grid<EditableOrder>("GridSrc")
.Datasource(Model)
.Caption("Order Grid")
.AutoFormat(Skins.Almond)
.ChildGrid(child =>
{
// Append the foreign key related to the parent
grid as a unique ID for the child grid.
child.ChildGridTemplate(Html.Syncfusion().Grid<OrderDetailEdit>("ChildG
rid_${OrderID}")
.Caption("OrderDetails Grid")
.Editing( edit=>{
edit.EditMode(GridEditMode.Normal);//
Specify the edit mode.
})
.ToChildGridTemplate());
})
%>
View [cshtml]
@{ Html.Syncfusion().Grid<EditableOrder>("GridSrc")
.Datasource(Model)
.Caption("Order Grid")
.AutoFormat(Skins.Almond)
.ChildGrid(child =>
{
// Append the foreign key related to the parent
grid as a unique ID for the child grid.
child.ChildGridTemplate(Html.Syncfusion().Grid<OrderDetailEdit>("ChildG
rid_${OrderID}")
.Caption("OrderDetails Grid")
.Editing( edit=>{
edit.EditMode(GridEditMode.Normal);//
Specify the edit mode.
})
.ToChildGridTemplate());
}) .Render();
}
12. In the controller, create a method to add new records to the grid as displayed below. In this
example, the repository method Add() is being created to insert records to the database.
Refer to the repository action method displayed below.
Controller
/// <summary>
/// Used to insert the record into the database and refresh the
grid.
/// </summary>
/// <param name="ord">Indicates editable order.</param>
/// <returns>HtmlActionResult returns the data displayed on the
grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult ChildAddOrder(OrderDetailEdit ord)
{
// Repository action method Add is used to insert records in
Note: Refer to repository action codes in Hierarchical Grid > Editing > OrderDetailRepository
Class.
13. In the controller, create a method to save changes, as displayed below. In this example, the
repository method Update() is used to update records to the data source.
Controller
/// Used to insert the record into the database and refresh the grid.
/// </summary>
/// <param name="ord">Indicates editable order.</param>
/// <returns>HtmlActionResult which returns data displayed on
the grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult ChildOrderSave(EditableOrder ord)
{
// Repository action method Update is used to update the
records in the data source.
OrderDetailRepository.Update(ord);
14. In the controller, create a method to delete the records from the database as displayed
below. In this example, the repository action Delete() will delete the record from the data
source.
Controller
/// <summary>
/// Used for deleting the records from the data source and
refreshing the grid.
/// </summary>
/// <param name="OrderID">Primary key values.</param>
/// <returns>HtmlActionResult returns the data displayed on the
grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult ChildDeleteOrder(int OrderID)
{
// Repository action Delete() deletes the given primary
value record from the data source.
OrderDetailRepository.Delete(OrderID);
180.
[Controller]
public ActionResult Index()
{
var data = new
NorthwindDataContext().Orders.Take(200).ToList();
return View(data);
181.
16. In order to work with paging actions, create a post method for the Index action and bind the
data source to the grid as shown in the following code:
182.
183.
[Controller]
/// <summary>
/// Paging action mapper, Paging Request is mapped here
/// </summary>
/// <param name="args">Contains Paging Information.</param>
/// <returns>HtmlActionResult which returns data displayed on
the Grid</returns>
[AcceptVerbs(HttpVerbs.Post)]public ActionResult Index(PagingParams
args)
{
IEnumerable data = new NorthwindDataContext
().Orders.Take(60).ToList();
return data.GridActions<Order>();
}
17. In order to work with the child grid, create a post method for the child grid and bind the data
source to the child grid as shown in the following code:
[Controller]
[AcceptVerbs(HttpVerbs.Post)]public ActionResult ChildGrid(PagingParams
args, int? OrderID)
{
IEnumerable data = new NorthwindDataContext
().Order_Details.Where(c=>c.OrderID == OrderID).ToList();
return data.GridActions<Order_Detail>();
}
18. Run the application. The grid will appear as shown below:
Perform the following steps to create a hierarchical grid through GridBuilder in JSON mode:
1. Create a model in the application (refer to How to > Adding model to the application).
2. Create the Grid control in the view and configure the properties.
<%=Html.Syncfusion().Grid<EmployeeView>("GridSrc")
.Caption("Employee Grid")
.AutoFormat(Skins.Almond)
.ActionMode(ActionMode.JSON)
.ChildGrid(child =>
{
// Append the foreign key related to the parent grid
as a unique ID for the child grid.
grid.child.ChildGridTemplate(Html.Syncfusion().Grid<OrdersView>("ChildG
rid_${EmployeeID}")
.Mappers(map =>
{
// Specify the foreign key related to the parent
grid.
// Separate action method for the child grid.
map.Action("JSONChildGrid", new {
EmployeeID = "${ EmployeeID}" });
})
.ToChildGridTemplate());
})
%>
View[cshtml]
@{
Html.Syncfusion().Grid<EmployeeView>("GridSrc")
.Datasource(Model)
.Caption("Employee Grid")
.AutoFormat(Skins.Almond)
.ActionMode(ActionMode.JSON)
.ChildGrid(child =>
{
child.ChildGridTemplate(Html.Syncfusion().Grid<OrdersView>("ChildGrid_$
{EmployeeID}").
.Mappers(map =>
{
// Specify the foreign key related to the parent
grid.
// Separate action method for the child grid.
map.Action("JSONChildGrid", new {
7. Enable editing by using the Editing method and configure the editing properties such as
AllowNew, AllowEdit, and AllowDelete, as displayed below.
View [ASPX]
<%=Html.Syncfusion().Grid<EditableOrder>("GridSrc")
.Datasource(Model)
.Caption("Order Grid")
.AutoFormat(Skins.Almond)
.ActionMode(ActionMode.JSON)
.ChildGrid(child =>
{
// Append the foreign key related to the parent
grid as a unique ID for the child grid.
child.ChildGridTemplate(Html.Syncfusion().Grid<OrderDetailEdit>("ChildG
rid_${OrderID}")
.Caption("OrderDetails Grid")
.Editing( edit=>{
edit.AllowEdit(true, "Home/ChildAddSave")// Specify the
action method that will perform the update action.
.AllowNew(true, "Home/ChildAddOrder")// Specify the
action method that will perform the insert action.
.AllowDelete(true, "Home/ChildDeleteOrder");//
Specify the action method that will perform the delete
action.
})
.ToChildGridTemplate());
})
%>
View [cshtml]
@{
Html.Syncfusion().Grid<EditableOrder>("GridSrc")
.Datasource(Model)
.Caption("Order Grid")
.AutoFormat(Skins.Almond)
.ActionMode(ActionMode.JSON)
.ChildGrid(child =>
{
// Append the foreign key related to the parent
grid as a unique ID for the child grid.
child.ChildGridTemplate(Html.Syncfusion().Grid<OrderDetailEdit>("ChildG
rid_${OrderID}")
.Caption("OrderDetails Grid")
.Caption("Orders")
.Editing( edit=>{
edit.AllowEdit(true, "Home/ChildOrderSave")// Specify
the action method that will perform the update action.
.AllowNew(true, "Home/ChildAddOrder")// Specify the
action method which that will perform the insert action.
.AllowDelete(true, "Home/ChildDeleteOrder");//
Specify the action method that will perform the delete action.
})
.ToChildGridTemplate());
})
.Render();
}
8. The Grid control allows users to add new records through grid toolbar items. In this
example, the AddNew, Edit, Delete, Save, and Cancel buttons have been added as
toolbar items in the following code example:
184.
View [ASPX]
<%=Html.Syncfusion().Grid<EditableOrder>("GridSrc")
.Datasource(Model)
.Caption("Order Grid")
.AutoFormat(Skins.Almond)
.ActionMode(ActionMode.JSON)
.ChildGrid(child =>
{
// Append the foreign key related to the parent
grid as a unique ID for the child grid.
child.ChildGridTemplate(Html.Syncfusion().Grid<OrderDetailEdit>("ChildG
rid_${OrderID}")
.Caption("OrderDetails Grid")
.ToolBar(tools =>
{
tools.Add(GridToolBarItems.AddNew)// Toolbar
item for inserting a record.
.Add(GridToolBarItems.Edit)// Toolbar
item for editing a record.
.Add(GridToolBarItems.Delete)// Toolbar
item for deleting a record.
.Add(GridToolBarItems.Update)// Toolbar
item for saving changes.
.Add(GridToolBarItems.Cancel);// Toolbar
item for canceling a
request.
})
.ToChildGridTemplate());
})
%>
185.
186.
View [cshtml]
@{
Html.Syncfusion().Grid<EditableOrder>("GridSrc")
.Datasource(Model)
.Caption("Order Grid")
.AutoFormat(Skins.Almond)
.ActionMode(ActionMode.JSON)
.ChildGrid(child =>
{
// Append the foreign key related to the parent
grid as a unique ID for the child grid.
child.ChildGridTemplate(Html.Syncfusion().Grid<OrderDetailEdit>("ChildG
rid_${OrderID}")
.Caption("OrderDetails Grid")
.Caption("Orders")
.ToolBar(tools =>
{
tools.Add(GridToolBarItems.AddNew)// Toolbar
item for inserting a record.
.Add(GridToolBarItems.Edit)// Toolbar
item for editing a record.
.Add(GridToolBarItems.Delete)// Toolbar
item for deleting a record.
.Add(GridToolBarItems.Update)// Toolbar
item for saving changes.
.Add(GridToolBarItems.Cancel);// Toolbar
item for canceling a
request.
})
.ToChildGridTemplate());
})
.Render();
}
9. Specify the Primary property, which uniquely identifies the grid record.
View [ASPX]
<%=Html.Syncfusion().Grid<EditableOrder>("GridSrc")
.Datasource(Model)
.Caption("Order Grid")
.AutoFormat(Skins.Almond)
.ActionMode(ActionMode.JSON)
.ChildGrid(child =>
{
// Append the foreign key related to the parent
grid as a unique ID for the child grid.
child.ChildGridTemplate(Html.Syncfusion().Grid<OrderDetailEdit>("ChildG
rid_${OrderID}")
.Caption("OrderDetails Grid")
.Editing( edit=>{
edit.PrimaryKey(key => key.Add(p =>
p.OrderID)); // Add a primary key to the primary key collections.
}) .ToChildGridTemplate());
})
%>
View [cshtml]
@{ Html.Syncfusion().Grid<EditableOrder>("GridSrc")
.Datasource(Model)
.Caption("Order Grid")
.AutoFormat(Skins.Almond)
.ActionMode(ActionMode.JSON)
.ChildGrid(child =>
{
// Append the foreign key related to the parent
grid as a unique ID for the child grid.
child.ChildGridTemplate(Html.Syncfusion().Grid<OrderDetailEdit>("ChildG
rid_${OrderID}")
.Caption("OrderDetails Grid")
.Editing( edit=>{
edit.PrimaryKey(key => key.Add(p =>
p.OrderID)); // Add a primary key to the primary key collections.
}) .ToChildGridTemplate());
}) .Render();
}
10. Specify the grid editing mode through the EditMode() method.
View [ASPX]
<%=Html.Syncfusion().Grid<EditableOrder>("GridSrc")
.Datasource(Model)
.Caption("Order Grid")
.AutoFormat(Skins.Almond)
.ActionMode(ActionMode.JSON)
.ChildGrid(child =>
{
// Append the foreign key related to the parent
grid as a unique ID for the child grid.
child.ChildGridTemplate(Html.Syncfusion().Grid<OrderDetailEdit>("ChildG
rid_${OrderID}")
.Caption("OrderDetails Grid")
.Editing( edit=>{
edit.EditMode(GridEditMode.Normal);//
Specify the edit mode.
})
.ToChildGridTemplate());
})
%>
View [cshtml]
@{ Html.Syncfusion().Grid<EditableOrder>("GridSrc")
.Datasource(Model)
.Caption("Order Grid")
.AutoFormat(Skins.Almond)
.ActionMode(ActionMode.JSON)
.ChildGrid(child =>
{
// Append the foreign key related to the parent
grid as a unique ID for the child grid.
child.ChildGridTemplate(Html.Syncfusion().Grid<OrderDetailEdit>("ChildG
rid_${OrderID}")
.Caption("OrderDetails Grid")
.Editing( edit=>{
edit.EditMode(GridEditMode.Normal); //
Specify the edit mode.
})
.ToChildGridTemplate());
}) .Render();
}
11. In the controller, create a method to add new records to the grid as displayed below. In this
example, the repository method Add() is being created to insert records into the database.
Refer to the repository action method displayed below.
Controller
/// <summary>
/// Used to insert the record into the database and refresh the
grid.
/// </summary>
/// <param name="ord">Indicates editable order.</param>
/// <returns>HtmlActionResult returns the data displayed on the
grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult ChildAddOrder(OrderDetailEdit ord)
{
// Repository action method Add is used to insert records in
the data source.
OrderDetailRepository.Add(ord);
Note: Refer to repository action codes in Hierarchical Grid > Editing > OrderDetailRepository
Class.
12. In the controller, create a method to save changes, as displayed below. In this example, the
repository method Update() is used to update records to the data source.
Controller
/// Used to insert the record into the database and refresh the grid.
/// </summary>
/// <param name="ord">Indicates editable order.</param>
/// <returns>HtmlActionResult returns data displayed on the
grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult ChildOrderSave(EditableOrder ord)
{
// Repository action method Update is used to update the
records in the data source.
OrderDetailRepository.Update(ord);
13. In the controller, create a method to delete the records from the database as displayed
below. In this example, the repository action Delete() will delete the record from the data
source.
Controller
/// <summary>
/// Used for deleting the records from the data source and
refreshing the grid.
/// </summary>
/// <param name="OrderID">Primary key values.</param>
/// <returns>HtmlActionResult returns the data displayed on the
grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult ChildDeleteOrder(int OrderID)
{
// Repository action Delete() deletes the given primary
value record from the data source.
OrderDetailRepository.Delete(OrderID);
[Controller]
public ActionResult Index()
{
return View();
15. In order to work with paging actions, create a post method for the Index action and bind the
data source to the grid as given in the following code sample:
[Controller]
/// <summary>
/// Used to bind the grid.
/// </summary>
/// <returns>View page displays the grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
var ordersData = new
NorthwindDataContext().EmployeeViews.ToList();
return ordersData.GridJSONActions<EmployeeView>();
}
16. In order to work with a child grid, create a post method for the child grid and bind the data
source to the child grid as shown in the following code:
[Controller]
/// <summary>
/// Used to bind the child grid.
/// </summary>
/// <returns>View page displays the grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult JSONChildGrid(PagingParams args, string
EmployeeID)
{
IEnumerable data = new
NorthwindDataContext().OrdersViews.Where(c => c.EmployeeID ==
EmployeeID).ToList();
return data.GridJSONActions<OrdersView>();
}
17. Run the application. The grid will appear as shown below:
You can effectively group extensive data with the help of multilevel stacked headers as well.
The skins applied to the grid are applied to the headers as well by default. Essential Grid has 14
built-in skins, and supports customizable themes as well.
Figure 239: Grid with “Product,” “Category,” and “Order Details” as Stacked Headers
Properties
Specifies
whether True
the
ShowStackedHeade False
stacked bool NA
r
header is Default value is
enabled or False
not
Specifies
the text to
be
HeaderText string Any string NA
displayed
in the
header
Specifies
the name
Name of the string Any string NA
stacked
header
Gets or
StackedColumnsColl List<GridStackedColumn
sets the
ection s<T>> GridStackedCol
Stacked NA
umns
columns
collection
Gets or
IList<GridStackedColum
sets the
NestedStackedColu ns<T>> GridStackedCol
nested NA
mns umns
columns
collections
Methods
Method Descrip Parameters Type Return Type
tion
StackedRows() Specifies Name, StackedRows IGridStackedHeaderB
the uilder<>
GridStackedRowBuild
Stacked
er<>
Header
Rows and
it is used
for
creating
stacked
header
rows.
The steps to work with the stacked header feature through GridBuilder are as follows:
View[ASPX]
<%=Html.Syncfusion().Grid<ProductCategory>("ProductGrid").Datasource(Mo
del)
.Caption("Product")
------
.Column(columns =>
{
columns.Add(c => c.ProductID);
columns.Add(c => c.ProductName);
columns.Add(c => c.CategoryID);
columns.Add(c => c.CategoryName);
columns.Add(c => c.Description);
columns.Add(c => c.UnitsInStock);
columns.Add(c => c.UnitPrice);
columns.Add(c => c.QuantityPerUnit);
})
.StackedHeader(sh =>
{
});
sh.StackedRows("Row2", sr2 =>
{
sr2.StackedColumn("Product Details", cc =>
{
cc.Add(c => c.ProductID);
cc.Add(c => c.ProductName);
});
sr2.StackedColumn("Category Details", c =>
{
c.Add(cc => cc.CategoryID);
c.Add(cc => cc.CategoryName);
c.Add(cc => cc.Description);
});
sr2.StackedColumn("Order Details", c =>
{
c.Add(cc => cc.UnitsInStock);
c.Add(cc => cc.UnitPrice);
c.Add(cc => cc.QuantityPerUnit);
});
});
})
.ShowStackedHeader(true)
%>
View[cshtml]
@{Html.Syncfusion().Grid<ProductCategory>("ProductGrid").Datasource(Mod
el)
.Caption("Product")
-------
.Column(columns =>
{
columns.Add(c => c.ProductID);
columns.Add(c => c.ProductName);
columns.Add(c => c.CategoryID);
columns.Add(c => c.CategoryName);
columns.Add(c => c.Description);
columns.Add(c => c.UnitsInStock);
columns.Add(c => c.UnitPrice);
columns.Add(c => c.QuantityPerUnit);
})
.StackedHeader(sh =>
{
sh.StackedRows("Row1", sr1 =>
{
sr1.StackedColumn("Products", ac =>
{
ac.Add(c => c.ProductID);
ac.Add(c => c.ProductName);
ac.Add(c => c.CategoryID);
ac.Add(c => c.CategoryName);
ac.Add(c => c.Description);
});
sr1.StackedColumn("Orders", ac =>
{
ac.Add(cc => cc.UnitsInStock);
ac.Add(cc => cc.UnitPrice);
ac.Add(cc => cc.QuantityPerUnit);
});
});
sh.StackedRows("Row2", sr2 =>
{
sr2.StackedColumn("Product Details", cc =>
{
cc.Add(c => c.ProductID);
cc.Add(c => c.ProductName);
});
sr2.StackedColumn("Category Details", c =>
{
c.Add(cc => cc.CategoryID);
c.Add(cc => cc.CategoryName);
c.Add(cc => cc.Description);
});
sr2.StackedColumn("Order Details", c =>
{
c.Add(cc => cc.UnitsInStock);
c.Add(cc => cc.UnitPrice);
c.Add(cc => cc.QuantityPerUnit);
});
});
})
.ShowStackedHeader(true).Render();
Controller
<%=Html.Syncfusion().Grid<ProductCategory>(
"ProductGrid1", "GridModel",
columns =>
{
columns.Add(c => c.ProductID);
columns.Add(c => c.ProductName);
columns.Add(c => c.CategoryID);
columns.Add(c => c.CategoryName);
columns.Add(c => c.Description);
columns.Add(c => c.UnitsInStock);
columns.Add(c => c.UnitPrice);
columns.Add(c => c.QuantityPerUnit);
}).Render();
%>
View[cshtml]
@{Html.Syncfusion().Grid<ProductCategory>(
"ProductGrid", "GridModel",
columns =>
{
columns.Add(c => c.ProductID);
columns.Add(c => c.ProductName);
columns.Add(c => c.CategoryID);
columns.Add(c => c.CategoryName);
columns.Add(c => c.Description);
columns.Add(c => c.UnitsInStock);
columns.Add(c => c.UnitPrice);
columns.Add(c => c.QuantityPerUnit);
}).Render();
4. Create a GridPropertiesModel in the Index method and assign the grid properties in the
model.
187.
Controller
ViewData["GridModel"] = gridModel;
Controller
Row1.HeaderText = "Row1";
Columns = new GridStackedColumns<ProductCategory>();
Columns.HeaderText = "Products";
Columns.NestedStackedColumns.Add(new
GridStackedColumns<ProductCategory>() { MappingName = "ProductID" });
Columns.NestedStackedColumns.Add(new
GridStackedColumns<ProductCategory>() { MappingName = "ProductName" });
Columns.NestedStackedColumns.Add(new
GridStackedColumns<ProductCategory>() { MappingName = "CategoryID" });
Columns.NestedStackedColumns.Add(new
gridModel.GridStackedRows.Add(Row1);
Row2.HeaderText = "Row2";
Columns = new GridStackedColumns<ProductCategory>();
Columns.HeaderText = "Product Details";
Columns.NestedStackedColumns.Add(new
GridStackedColumns<ProductCategory>() { MappingName = "ProductID" });
Columns.NestedStackedColumns.Add(new
GridStackedColumns<ProductCategory>() { MappingName = "ProductName" });
Row2.StackedColumnsCollection.Add(Columns);
gridModel.GridStackedRows.Add(Row2);
6. Create a post method for Stacked Header action and bind the data source to grid as like
below code.
Controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult StackedHeader(PagingParams args)
{
IEnumerable data = new
NorthwindDataContext().ProductCategories.Take(200).ToList();
return data.GridJSONActions<ProductCategory>();
}
}
Sample Link
To view the samples, follow the steps below:
1. Open the Grid sample browser from the dashboard (Refer to the Samples and Location
chapter).
2. Navigate to Grid.MVC > Rows and Columns > StackedHeader
MergeCellEventArgs Properties
Property Description Type Data Type
GridCell Gets or sets the ColSpan value for GridTableCell<T> Grid cells
MergeCell.
RangeInfo Gets or sets the RowSpan value for GridCellRangeInfo<T> Grid cell
MergeCell. range info
GridCellRangeInfo Properties
Property Description Type Data Type
RowSpan Gets or sets RowSpan value for int Any Number
MergeCell.
Methods
Method Description Parameters Type Return Type
SetRange RowSpan and Int args1, int args2 int void
ColSpan values.
Client-Side Events
Event Description Arguments Type
MergeCellInfo Gets or sets MergeCellInfo String IGridBuilder<T>
event handler.
Server Events
Event Description Arguments Type
3. Add the following code in the Index.aspx file to create the Grid control in the view.
View [cshtml]
@(Html.Syncfusion().Grid<OrderDetailsView>("OrderDetails_grid")
.Datasource(Model)
.Caption("Orders")
.EnablePaging()
.EnableRowHover(false)
.ActionMode(ActionMode.Server)
.AutoFormat(Skins.Marble)
.Column(column =>
{
column.Add(p =>
p.OrderID).Width(110).TextAlign(TextAlignment.Right).HeaderText("Order
ID");
column.Add(p =>
p.ProductID).Width(100).TextAlign(TextAlignment.Right).HeaderText("Product
ID");
column.Add(p => p.ProductName).HeaderText("Product
Name");
column.Add(P =>
P.Quantity).Width(100).TextAlign(TextAlignment.Right);
column.Add(p =>
p.UnitPrice).Width(100).TextAlign(TextAlignment.Right).Format("{0:C}").Head
erText("Unit Price");
column.Add(p =>
p.ExtendedPrice).HeaderText("Extended Price").Width(110);
})
.AllowMergeCells(true)
.MergeCellInfo((sender,args) =>
Html.RenderAction("QueryAction", "GridCellMerging", new { sender = this,
args = args }))
View [ASPX]
<%=Html.Syncfusion().Grid<OrderDetailsView>("OrderDetails_grid")
.Datasource(Model)
.Caption("Orders")
.EnablePaging()
.EnableRowHover(false)
.ActionMode(ActionMode.Server)
.AutoFormat(Skins.Marble)
.Column(column =>
{
column.Add(p =>
p.OrderID).Width(110).TextAlign(TextAlignment.Right).HeaderText("Order
ID");
column.Add(p =>
p.ProductID).Width(100).TextAlign(TextAlignment.Right).HeaderText("Product
ID");
column.Add(p => p.ProductName).HeaderText("Product
Name");
column.Add(P =>
P.Quantity).Width(100).TextAlign(TextAlignment.Right);
column.Add(p =>
p.UnitPrice).Width(100).TextAlign(TextAlignment.Right).Format("{0:C}").Head
erText("Unit Price");
column.Add(p =>
p.ExtendedPrice).HeaderText("Extended Price").Width(110);
})
.AllowMergeCells(true)
.MergeCellInfo((sender,args) =>
Html.RenderAction("QueryAction", "GridCellMerging", new { sender = this,
args = args }))
%>
[Controller – C#]
//
// GET: /GridCellMerging/
public ActionResult Index ()
{
var data = new NorthwindDataContext().OrderDetailsViews;
return View(data);
}
[Controller - VB]
'
' GET: /GridCellMerging/
Public Function Index() As ActionResult
Dim data = New NorthwindDataContext ().OrderDetailsViews
Return View(data)
End Function
5. In order to work with paging and sorting actions, create a Post method for Index actions
and bind the data source to the grid as shown in the following code.
[Controller – C#]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult ServerCellMerging(PagingParams args)
{
IEnumerable data = new
NorthwindDataContext().OrderDetailsViews;
ActionResult result = data.GridActions<OrderDetailsView>();
var engineSource = result as
GridHtmlActionResult<OrderDetailsView>;
engineSource.GridModel.MergeCellInfo = QueryAction;
return engineSource;
}
{
if (args.GridCell.Text.ToString() == "5")
args.RangeInfo.SetRange(2, 1);
}
else if (args.GridCell.Column.MappingName == "UnitPrice" &&
args.RangeInfo.RowIndex == 3)
{
if (args.GridCell.Text.ToString() == "$34.80")
args.RangeInfo.SetRange(2, 1);
}
else if (args.GridCell.Column.MappingName ==
"ExtendedPrice" && args.RangeInfo.RowIndex == 3)
{
if (args.GridCell.Text.ToString() == "174.0000")
args.RangeInfo.SetRange(2, 1);
}
}
}
[Controller – VB]
<AcceptVerbs(HttpVerbs.Post)> _
Public Function ServerCellMerging(ByVal args As PagingParams) As
ActionResult
Dim data As IEnumerable = New
NorthwindDataContext().OrderDetailsViews
Dim result As ActionResult = data.GridActions(Of
OrderDetailsView)()
Dim engineSource = TryCast(result, GridHtmlActionResult(Of
OrderDetailsView))
engineSource.GridModel.MergeCellInfo = QueryAction
Return engineSource
End Function
Public Sub QueryAction(ByVal sender As GridPropertiesModel(Of
OrderDetailsView), ByVal args As MergeCellEventArgs(Of OrderDetailsView))
If args.GridCell.TableCellType =
GridTableCellType.RecordFieldCell Then
If args.GridCell.Column.MappingName = "OrderID" AndAlso
args.RangeInfo.RowIndex = 1 Then
If args.GridCell.Text.ToString() = "10248" Then
args.RangeInfo.SetRange(3, 1)
End If
ElseIf args.GridCell.Column.MappingName = "OrderID" AndAlso
args.RangeInfo.RowIndex = 4 Then
If args.GridCell.Text.ToString() = "10249" Then
args.RangeInfo.SetRange(2, 1)
End If
ElseIf args.GridCell.Column.MappingName = "OrderID" AndAlso
args.RangeInfo.RowIndex = 6 Then
If args.GridCell.Text.ToString() = "10250" Then
args.RangeInfo.SetRange(3, 1)
End If
1. Create a model in the application (Refer to How to > Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. Add the following code in the Index.aspx file to create the Grid control in the view.
View [cshtml]
@(Html.Syncfusion().Grid<OrderDetailsView>("OrderDetails_grid",
"GridModel", column =>
{
column.Add(p =>
p.OrderID).Width(110).TextAlign(TextAlignment.Right).HeaderText("Order
ID");
column.Add(p =>
p.ProductID).Width(100).TextAlign(TextAlignment.Right).HeaderText("Product
ID");
column.Add(p => p.ProductName).HeaderText("Product
Name");
column.Add(P =>
P.Quantity).Width(100).TextAlign(TextAlignment.Right);
column.Add(p =>
p.UnitPrice).Width(100).TextAlign(TextAlignment.Right).Format("{0:C}").Head
erText("Unit Price");
column.Add(p =>
p.ExtendedPrice).HeaderText("Extended Price").Width(110);
}))
View [ASPX]
<%= Html.Syncfusion().Grid<OrderDetailsView>("OrderDetails_grid",
"GridModel", column =>
{
column.Add(p =>
p.OrderID).Width(110).TextAlign(TextAlignment.Right).HeaderText("Order
ID");
column.Add(p =>
p.ProductID).Width(100).TextAlign(TextAlignment.Right).HeaderText("Product
ID");
column.Add(p => p.ProductName).HeaderText("Product
Name");
column.Add(P =>
P.Quantity).Width(100).TextAlign(TextAlignment.Right);
column.Add(p =>
p.UnitPrice).Width(100).TextAlign(TextAlignment.Right).Format("{0:C}").Head
erText("Unit Price");
column.Add(p =>
p.ExtendedPrice).HeaderText("Extended Price").Width(110);
})
%>
4. Create a GridPropertiesModel in the Index method. Bind the data source using the
DataSource property and pass the model from controller to view using the ViewData class
as demonstrated in the following code.
[Controller]
//
// GET: /ServerModel/
5. In order to work with paging and sorting actions, create a Post method for Index actions
and bind the data source to the grid as shown in the following code.
[Controller – C#]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index (PagingParams args)
{
IEnumerable data = new
NorthwindDataContext().OrderDetailsViews;
return data.GridActions <OrderDetailsView>();
}
[Controller – VB]
<AcceptVerbs(HttpVerbs.Post)> _
Public Function Index(ByVal args As PagingParams) As ActionResult
Dim data As IEnumerable = New NorthwindDataContext
().OrderDetailsViews
Return data.GridActions (Of OrderDetailsView)()
End Function
6. Run the application. The grid will appear as shown in the following figure.
Sample Link
To view the samples, follow the steps below:
1. Open the Grid sample browser from the dashboard (Refer to the Samples and Location
chapter).
2. Navigate to Grid.MVC > Cell Merging > Server Merging
View [cshtml]
@(Html.Syncfusion().Grid<OrderDetailsView>("OrderDetails_grid")
.Datasource(Model)
.Caption("Orders")
.EnablePaging()
.ActionMode(ActionMode.JSON)
.AutoFormat(Skins.Marble)
.AllowMergeCells(true)
.Column(column =>
{
column.Add(p =>
p.OrderID).Width(110).TextAlign(TextAlignment.Right).HeaderText("Order
ID");
column.Add(p =>
p.ProductID).Width(100).TextAlign(TextAlignment.Right).HeaderText("Product
ID");
column.Add(p => p.ProductName).HeaderText("Product
Name");
column.Add(P =>
P.Quantity).Width(100).TextAlign(TextAlignment.Right);
column.Add(p =>
p.UnitPrice).Width(100).TextAlign(TextAlignment.Right).Format("{0:C}").Head
erText("Unit Price");
column.Add(p =>
p.ExtendedPrice).HeaderText("Extended Price").Width(110);
})
.ClientSideEvents(ce =>
{
ce.MergeCellInfo("MergeCellInfo");
}))
<script type="text/javascript">
function MergeCellInfo(sender, args) {
if (args.GridCell.Column.Member == "OrderID") {
if (args.GridCell.Text.toString() == "10248" && args.RowIndex
== 1)
args.SetRange(3, 1);
else if (args.GridCell.Text.toString() == "10249" &&
args.RowIndex == 4)
args.SetRange(2, 1);
else if (args.GridCell.Text.toString() == "10250" &&
args.RowIndex == 6)
args.SetRange(3, 1);
else if (args.GridCell.Text.toString() == "10251" &&
args.RowIndex == 9)
args.SetRange(3, 1);
}
if (args.GridCell.Column.Member == "ProductName" && args.RowIndex
== 3) {
if (args.GridCell.Text.toString() == "Mozzarella di Giovanni")
args.SetRange(2, 1);
}
else if (args.GridCell.Column.Member == "Quantity" && args.RowIndex
== 3) {
if (args.GridCell.Text.toString() == "5")
args.SetRange(2, 1);
}
else if (args.GridCell.Column.Member == "UnitPrice" &&
args.RowIndex == 3) {
if (args.GridCell.Text.toString() == "$34.80")
args.SetRange(2, 1);
}
else if (args.GridCell.Column.Member == "ExtendedPrice" &&
args.RowIndex == 3) {
if (args.GridCell.Text.toString() == "174")
args.SetRange(2, 1);
}
}
</script>
View [ASPX]
<%=Html.Syncfusion().Grid<OrderDetailsView>("OrderDetails_grid")
.Datasource(Model)
.Caption("Orders")
.EnablePaging()
.ActionMode(ActionMode.JSON)
.AutoFormat(Skins.Marble)
.AllowMergeCells(true)
.Column(column =>
{
column.Add(p =>
p.OrderID).Width(110).TextAlign(TextAlignment.Right).HeaderText("Order
ID");
column.Add(p =>
p.ProductID).Width(100).TextAlign(TextAlignment.Right).HeaderText("Product
ID");
column.Add(p => p.ProductName).HeaderText("Product
Name");
column.Add(P =>
P.Quantity).Width(100).TextAlign(TextAlignment.Right);
column.Add(p =>
p.UnitPrice).Width(100).TextAlign(TextAlignment.Right).Format("{0:C}").Head
erText("Unit Price");
column.Add(p =>
p.ExtendedPrice).HeaderText("Extended Price").Width(110);
})
.ClientSideEvents(ce =>
{
ce.MergeCellInfo("MergeCellInfo");
})
%>
<script type="text/javascript">
function MergeCellInfo(sender, args) {
if (args.GridCell.Column.Member == "OrderID") {
if (args.GridCell.Text.toString() == "10248" && args.RowIndex
== 1)
args.SetRange(3, 1);
else if (args.GridCell.Text.toString() == "10249" &&
args.RowIndex == 4)
args.SetRange(2, 1);
else if (args.GridCell.Text.toString() == "10250" &&
args.RowIndex == 6)
args.SetRange(3, 1);
else if (args.GridCell.Text.toString() == "10251" &&
args.RowIndex == 9)
args.SetRange(3, 1);
}
if (args.GridCell.Column.Member == "ProductName" && args.RowIndex
== 3) {
if (args.GridCell.Text.toString() == "Mozzarella di Giovanni")
args.SetRange(2, 1);
}
else if (args.GridCell.Column.Member == "Quantity" && args.RowIndex
== 3) {
if (args.GridCell.Text.toString() == "5")
args.SetRange(2, 1);
}
else if (args.GridCell.Column.Member == "UnitPrice" &&
args.RowIndex == 3) {
if (args.GridCell.Text.toString() == "$34.80")
args.SetRange(2, 1);
}
else if (args.GridCell.Column.Member == "ExtendedPrice" &&
args.RowIndex == 3) {
if (args.GridCell.Text.toString() == "174")
args.SetRange(2, 1);
}
}
</script>
188.
4. Set its data source and render the view.
189.
[Controller – C#]
//
// GET: / JsonCellMerging /
public ActionResult Index ()
{
var data = new NorthwindDataContext().OrderDetailsViews;
return View(data);
[Controller - VB]
'
' GET: / JsonCellMerging /
Public Function Index() As ActionResult
Dim data = New NorthwindDataContext ().OrderDetailsViews
Return View(data)
End Function
190.
5. In order to work with paging and sorting actions, create a Post method for Index actions
and bind the data source to the grid as shown in the following code.
191.
[Controller – C#]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index (PagingParams args)
{
IEnumerable data = new
NorthwindDataContext().OrderDetailsViews;
return data.GridJSONActions <OrderDetailsView>();
}
[Controller – VB]
<AcceptVerbs(HttpVerbs.Post)> _
Public Function Index(ByVal args As PagingParams) As ActionResult
Dim data As IEnumerable = New NorthwindDataContext
().OrderDetailsViews
Return data.GridJSONActions (Of OrderDetailsView)()
End Function
192.
6. Run the application. The grid will appear as shown in the following figure.
@(Html.Syncfusion().Grid<OrderDetailsView>("OrderDetails_grid",
"GridModel", column =>
{
column.Add(p =>
p.OrderID).Width(110).TextAlign(TextAlignment.Right).HeaderText("Order
ID");
column.Add(p =>
p.ProductID).Width(100).TextAlign(TextAlignment.Right).HeaderText("Product
ID");
column.Add(p => p.ProductName).HeaderText("Product
Name");
column.Add(P =>
P.Quantity).Width(100).TextAlign(TextAlignment.Right);
column.Add(p =>
p.UnitPrice).Width(100).TextAlign(TextAlignment.Right).Format("{0:C}").Head
erText("Unit Price");
column.Add(p =>
p.ExtendedPrice).HeaderText("Extended Price").Width(110);
}))
View [ASPX]
<%= Html.Syncfusion().Grid<OrderDetailsView>("OrderDetails_grid",
"GridModel", column =>
{
column.Add(p =>
p.OrderID).Width(110).TextAlign(TextAlignment.Right).HeaderText("Order
ID");
column.Add(p =>
p.ProductID).Width(100).TextAlign(TextAlignment.Right).HeaderText("Product
ID");
column.Add(p => p.ProductName).HeaderText("Product
Name");
column.Add(P =>
P.Quantity).Width(100).TextAlign(TextAlignment.Right);
column.Add(p =>
p.UnitPrice).Width(100).TextAlign(TextAlignment.Right).Format("{0:C}").Head
erText("Unit Price");
column.Add(p =>
p.ExtendedPrice).HeaderText("Extended Price").Width(110);
})
%>
4. Create a GridPropertiesModel in the Index method. Bind the data source using the
DataSource property and pass the model from controller to view using the ViewData class
as shown in the following sample.
193.
[Controller – C#]
//
// GET: /JsonModel/
};
ViewData["GridModel"] = model;
return View(ViewData["GridModel"]);
}
[Controller – VB]
'
' GET: /JsonModel/
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index (PagingParams args)
{
IEnumerable data = new
NorthwindDataContext().OrderDetailsViews;
return data.GridJSONActions <OrderDetailsView>();
}
[Controller – VB]
<AcceptVerbs(HttpVerbs.Post)> _
Public Function Index(ByVal args As PagingParams) As ActionResult
Dim data As IEnumerable = New NorthwindDataContext
().OrderDetailsViews
Return data.GridJSONActions (Of OrderDetailsView)()
End Function
196.
6. Run the application. The grid will appear as shown below.
197.
Sample Link
To view the samples, follow the steps below:
1. Open the Grid sample browser from the dashboard (Refer to the Samples and Location
chapter).
2. Navigate to Grid.MVC > Cell Merging > JSON Merging
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.AutoFormat(Skins. Marble)
.FrozenRows(2)
.FrozenColumns(1)
.EnableScrolling()
.Scrolling(scroll => scroll.Height(150).Width(535))
.Column( columns => {
columns.Add(p => p.OrderID).Width(200);
columns.Add(p => p.CustomerID).Width(200);
columns.Add(p => p.EmployeeID).Width(200);
columns.Add(P => P.ShipCountry).Width(200);
columns.Add(p => p.OrderDate).Width(200).Format("{0:dd-MM-
yyyy}");
})
%>
View [cshtml]
@{ Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.AutoFormat(Skins.Marble)
.FrozenRows(2)
.FrozenColumns(1)
.EnableScrolling()
.Scrolling(scroll => scroll.Height(150).Width(535))
.Column( columns => {
columns.Add(p => p.OrderID).Width(200);
columns.Add(p => p.CustomerID).Width(200);
columns.Add(p => p.EmployeeID).Width(200);
columns.Add(P => P.ShipCountry).Width(200);
columns.Add(p => p.OrderDate).Width(200).Format("{0:dd-MM-
yyyy}");
}).Render();
}
[Controller]
/// <summary>
/// Used for rendering the grid initially.
/// </summary>
/// <returns>View page, it displays the Grid</returns>
public ActionResult Index()
{
var data = new NorthwindDataContext().Orders;
return View(data);
}
8. Run the application. The grid will appear as displayed in the following screenshot:
Figure 246: “OrderID” Column and First Two Rows Visible after Scrolling
199.
View [cshtml]
@{
Html.Syncfusion().Grid<Order>("Grid1","GridModel", columns => {
columns.Add(p => p.OrderID).Width(200);
columns.Add(p => p.CustomerID).Width(200);
columns.Add(p => p.EmployeeID).Width(200);
columns.Add(P => P.ShipCountry).Width(200);
columns.Add(p => p.OrderDate).Width(200).Format("{0:dd-MM-
yyyy}");
}).Render();
}
4. Create a GridPropertiesModel in the Index method. Use the Localize property to specify
the culture details.
[Controller]
FrozenColumns = 1,
Width = 635,
Height = 150,
AllowScrolling = true
};
ViewData["GridModel"] = gridModel;
return View();
}
5. Run the application, the grid will appear as shown in the following screenshot:
Figure 248: “OrderID” Column and First Two Rows Visible after Scrolling
Sample Link
To view the samples, follow the steps below:
1. Open the Grid sample browser from the dashboard (Refer to the Samples and Location
chapter).
2. Navigate to Grid.MVC > Rows and Columns > Frozen rows and columns
Methods
set_frozenColumns
Gets or sets the (int frozenColumns) Client-side Void
number of
columns that
need to be
frozen. Scrolling
should be
enabled and grid
width should be
less than the
total columns
width.
freezePanes
Keep the rows No Argumnets Client-side Boolean
and columns
visible while Grid
scrolls based on
the current
selection.
unFreezePanes
Unlock all rows No Arguments Client-side Void
and columns to
scroll through
the entire grid.
[JavaScript]
grid.freezePanes();
If the third row and second column of the grid is selected, freeze panes will keep the first two
rows and first column visible as always while the grid is scrolling.
[JavaScript]
Unlock all the rows and columns to scroll through the entire grid.
4.21.1.4 Appearance
The following screenshot displays a dark border, indicating columns and rows that are frozen.
The following figures illustrate the appearance and structure of the auto wrap feature and its
settings:
Notes:
ClipContent is only enabled when AutoWrap is enabled.
ResizeToFit doesn’t depend on the AutoWrap property.
4.22.1 Properties
Type of Value it
Property Description Dependencies
Property Accepts
Depends on the
Specifies whether the
AllowResizing
autowrap is enabled
property.
True If AllowResizing is
AllowAutoWrap Content will wrap to bool
False true, then you have
the next line if the
the option of
content exceeds the
enabling the
boundary of the
AllowAutoWrap
Column Cells
property.
Depends on the
Specifies whether the ResizeSettings—
cell content will be True
ClipContent bool
clipped on column False ClipContent is a
resizing sub-property of
ResizeSettings
Events
Event Description Arguments Type Reference links
Using the OnRecordCollapsing event, users can avoid a collapse event. Using the
OnRecordExpanding event, users can avoid an expand event.
The client-side events are used in ASPX as shown below in server mode through GridBuilder:
View[ASPX]
<%=Html.Syncfusion().Grid<Order>("GridSrc")
.Datasource(Model)
.Caption("Order Grid")
.AutoFormat(Skins.Almond)
.AllowResizing(true)
.ClientSideEvents(eve =>
{
eve. OnResizingStart ("OnResizingStart ");
eve. OnResizingEnd ("OnResizingEnd ");
eve. Resized ("Resized ");
})
%>
For Razor, use the code shown below in server mode through GridBuilder.
View[cshtml]
@{
Html.Syncfusion().Grid<Order>("GridSrc")
.Datasource(Model)
.Caption("Order Grid")
.AutoFormat(Skins.Almond)
. AllowResizing(true)
.ClientSideEvents(eve =>
{
eve. OnResizingStart ("OnResizingStart ");
eve. OnResizingEnd ("OnResizingEnd ");
eve. Resized ("Resized ");
})
.Render();
}
The steps to work with the auto wrap feature through GridBuilder are as follows:
View[ASPX]
<%=Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model)
.Caption("Orders")
--------
--------
.AutoFormat(Skins.Sandune)
.AllowResizing(true)
.AllowAutoWrap(true)
.ResizeSettings(resize => {
resize.ResizeToFit(true);
resize.ClipContent(true);
})
%>
View[cshmtl]
@{Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model)
.Caption("Orders")
--------
--------
.AutoFormat(Skins.Sandune)
.AllowResizing(true)
.AllowAutoWrap(true)
.ResizeSettings(resize => {
resize.ResizeToFit(true);
resize.ClipContent(true);
}).Render();
}
Controller
<%=Html.Syncfusion().Grid<EditableOrder>(
"Grid1", "GridModel",
column =>
{
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.CustomerID).HeaderText("Customer
ID");
column.Add(p => p.ShipCountry).HeaderText("Ship
Country");
column.Add(p => p.OrderDate).HeaderText("Order
Date");
column.Add(p => p.Freight).HeaderText("Freight");
})
%>
View[cshtml]
@{Html.Syncfusion().Grid<EditableOrder>(
"Grid1", "GridModel",
column =>
{
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.CustomerID).HeaderText("Customer
ID");
column.Add(p => p.ShipCountry).HeaderText("Ship
Country");
column.Add(p => p.OrderDate).HeaderText("Order
Date");
column.Add(p => p.Freight).HeaderText("Freight");
})
%>
Controller
gridModel.ResizeSettings = resize;
200.
5. Create a Post method for AutoWrap actions and bind the data source to the grid as given
in the following code:
201.
Controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AutoWrap(PagingParams args, int? OrderID,
GridEditMode? GridMode)
{
IEnumerable data = OrderRepository.GetAllRecords();
return data.GridJSONActions<EditableOrder>();
}
Sample Link
To view the samples, follow the steps below:
1. Open the Grid sample browser from the dashboard (Refer to the Samples and Location
chapter).
2. Navigate to Grid.MVC > Rows and Columns > AutoWrap Column Cells
Right
Left,
Right
Events
Name Description Arguments Reference
type
OnLoad Triggered when the grid is GridObject // returns grid NA
initialized in client side. object
RequestType // returns
request type
MappingURL // returns
mapping url
_currentItemIndex contains
the index of the current
clicked toolbar item
_disabled specifies whether
the current clicked toolbar
item is disabled or not.
_itemType specifies
whether the current clicked
toolbar item is a built-in item
or custom item.
deletedRecords—
contains the list of
deleted records.
insertedRecords—
contains the list of
inserted records.
value—Contains the
value of the cell
being edited.
value—Contains the
updated value of
the cell.
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.AutoFormat(Skins.Sandune)
.AllowDragAndDrop(true)
.Droppable(true)
.Column( columns => {
columns.Add(p => p.OrderID).HeaderText("Order ID");
columns.Add(p => p.CustomerID).HeaderText("Customer ID");
columns.Add(p => p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship Country");
columns.Add(p => p.OrderDate).HeaderText("Order
Date").Format("{0:dd-MM-yyyy}");
})
.ClientSideEvents(events =>
{
events.AfterDrop("AfterDrop");
events.BeforeDrop("BeforeDrop");
events.MouseUpDrop("MouseUpDrop");
events.OnActionBegin("OnActionBegin");
events.OnActionComplete("OnActionComplete");
events.OnActionFailure("OnActionFailure");
events.OnActionSuccess("OnActionSuccess");
events.OnBeforeContextMenuOpen("OnBeforeContextMenuOpen");
events.OnBulkSave("OnBulkSave");
events.OnCancel("OnCancel");
events.OnCellEdit("OnCellEdit");
events.OnCellSave("OnCellSave");
events.OnContextMenuClose("OnContextMenuClose");
events.OnContextMenuItemClick("OnContextMenuItemClick");
events.OnContextMenuOpen("OnContextMenuOpen");
events.OnCustomUnboundCellClickHandler("OnCustomUnboundCellClickHandler
");
events.OnDragStart("OnDragStart");
events.OnGridRowDragEvent("OnGridRowDragEvent");
events.OnGridRowsDropEvent("OnGridRowsDropEvent");
events.OnLoad("OnLoad");
events.OnRecordAddNew("OnRecordAddNew");
events.OnRecordCollapsed("OnRecordCollapsed");
events.OnRecordCollapsing("OnRecordCollapsing");
events.OnRecordDoubleClickEvent("OnRecordDoubleClickEvent");
events.OnRecordEdit("OnRecordEdit");
events.OnRecordExpanded("OnRecordExpanded");
events.OnRecordExpanding("OnRecordExpanding");
events.OnRecordHoverEvent("OnRecordHoverEvent");
events.OnRecordSelectionEvent("OnRecordSelectionEvent");
events.OnRecordsUnselectionEvent("OnRecordsUnselectionEvent");
events.OnResizingEnd("OnResizingEnd");
events.OnResizingStart("OnResizingStart");
events.OnRowDragStarted("OnRowDragStarted");
events.OnRowDropped("OnRowDropped");
events.OnRowDropping("OnRowDropping");
events.OnToolbarClickEvent("OnToolbarClickEvent");
events.Resized("Resized");
events.MergeCellInfo("MergeCellInfo");
events.QueryCellInfo("QueryCellInfo");
events.RowDataBound("RowDataBound");
})
%>
View [cshtml]
@{ Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.AutoFormat(Skins.Sandune)
.Column( columns => {
columns.Add(p => p.OrderID).HeaderText("Order ID");
columns.Add(p => p.CustomerID).HeaderText("Customer ID");
columns.Add(p => p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship Country");
columns.Add(p => p.OrderDate).HeaderText("Order
Date").Format("{0:dd-MM-yyyy}");
})
.ClientSideEvents(events =>
{
events.AfterDrop("AfterDrop");
events.BeforeDrop("BeforeDrop");
events.MouseUpDrop("MouseUpDrop");
events.OnActionBegin("OnActionBegin");
events.OnActionComplete("OnActionComplete");
events.OnActionFailure("OnActionFailure");
events.OnActionSuccess("OnActionSuccess");
events.OnBeforeContextMenuOpen("OnBeforeContextMenuOpen");
events.OnBulkSave("OnBulkSave");
events.OnCancel("OnCancel");
events.OnCellEdit("OnCellEdit");
events.OnCellSave("OnCellSave");
events.OnContextMenuClose("OnContextMenuClose");
events.OnContextMenuItemClick("OnContextMenuItemClick");
events.OnContextMenuOpen("OnContextMenuOpen");
events.OnCustomUnboundCellClickHandler("OnCustomUnboundCellClickHandler
");
events.OnDragStart("OnDragStart");
events.OnGridRowDragEvent("OnGridRowDragEvent");
events.OnGridRowsDropEvent("OnGridRowsDropEvent");
events.OnLoad("OnLoad");
events.OnRecordAddNew("OnRecordAddNew");
events.OnRecordCollapsed("OnRecordCollapsed");
events.OnRecordCollapsing("OnRecordCollapsing");
events.OnRecordDoubleClickEvent("OnRecordDoubleClickEvent");
events.OnRecordEdit("OnRecordEdit");
events.OnRecordExpanded("OnRecordExpanded");
events.OnRecordExpanding("OnRecordExpanding");
events.OnRecordHoverEvent("OnRecordHoverEvent");
events.OnRecordSelectionEvent("OnRecordSelectionEvent");
events.OnRecordsUnselectionEvent("OnRecordsUnselectionEvent");
events.OnResizingEnd("OnResizingEnd");
events.OnResizingStart("OnResizingStart");
events.OnRowDragStarted("OnRowDragStarted");
events.OnRowDropped("OnRowDropped");
events.OnRowDropping("OnRowDropping");
events.OnToolbarClickEvent("OnToolbarClickEvent");
events.Resized("Resized");
events.MergeCellInfo("MergeCellInfo");
events.QueryCellInfo("QueryCellInfo");
events.RowDataBound("RowDataBound");
}).Render();
}
OnRecordSelectionEvent = "OnRecordSelectionEvent";
OnRecordsUnselectionEvent =
"OnRecordsUnselectionEvent";
OnResizingEnd = "OnResizingEnd";
OnResizingStart = "OnResizingStart";
OnRowDragStarted = "OnRowDragStarted";
OnRowDropped = "OnRowDropped";
OnRowDropping = "OnRowDropping";
OnToolbarClickEvent = "OnToolbarClickEvent";
Resized = "Resized";
MergeCellInfo = "MergeCellInfo";
QueryCellInfo = "QueryCellInfo";
RowDataBound = "RowDataBound";
};
gridObj.add_OnBeforeContextMenuOpen(OnBeforeContextMenuOpen);
gridObj.add_OnContextMenuOpen(OnContextMenuOpen);
gridObj.add_OnContextMenuItemClick(OnContextMenuItemClick);
gridObj.add_OnResizeHandleDblClick(OnResizeHandleDblClick);
gridObj.add_OnCustomUnboundCellClickHandler(OnCustomUnboundCellClick);
gridObj.add_OnContextMenuClose(OnContextMenuClose);
gridObj.add_OnRowSelect(OnRowSelect);
gridObj.add_OnRowHover(OnRowHover);
gridObj.add_OnRowsSelected(OnRowsSelected);
gridObj.add_OnDroppingTarget(OnDroppingTarget);
gridObj.add_OnDropTargetCompleted(OnDropTargetCompleted);
gridObj.add_OnDoubleClick(OnDoubleClick);
gridObj.add_QueryCellInfo(QueryCellInfo);
gridObj.add_MergeCellInfo(MergeCellInfo);
gridObj.add_RowDataBound(RowDataBound);
gridObj.add_OnCancel(OnCancel);
gridObj.add_OnRecordAddNew(OnRecordAddNew);
gridObj.add_OnRecordEdit(OnRecordEdit);
gridObj.add_OnRecordsUnselectionEvent(OnRecordsUnselectionEvent);
gridObj.add_OnDroponGridRowsEvent(OnDroponGridRowsEvent);
gridObj.add_OnDragonGridRowEvent(OnDragonGridRowEvent);
gridObj.add_OnLoad(OnLoad);
gridObj.add_OnActionFailure(OnActionFailure);
gridObj.add_OnActionComplete(OnActionComplete);
gridObj.add_OnActionBegin(OnActionBegin);
gridObj.add_OnCellEdit(OnCellEdit);
gridObj.add_OnCellSave(OnCellSave);
gridObj.add_OnBulkSave(OnBulkSave);
gridObj.add_OnActionSuccess(OnActionSuccess);
gridObj.add_onResizingStart(onResizingStart);
gridObj.add_onResizingEnd(onResizingEnd);
gridObj.add_Resized(Resized);
gridObj.add_onDragStart(onDragStart);
gridObj.add_beforeDrop(beforeDrop);
gridObj.add_afterDrop(afterDrop);
gridObj.add_MouseUpDrop(MouseUpDrop);
gridObj.add_OnToolbarClickEvent(OnToolbarClickEvent);
gridObj.add_OnRecordExpanding(OnRecordExpanding);
gridObj.add_OnRecordExpanded(OnRecordExpanded);
gridObj.add_OnRecordCollapsing(OnRecordCollapsing);
gridObj.add_OnRecordCollapsed(OnRecordCollapsed);
Events Arguments
OnCellEdit colObj:
OnCancel
AllowAutoWrap
OnCellSave
Events Arguments
OnRecordSelectionEvent AllowEditing
OnRecordsUnselectionEvent
AllowFilter
OnRecordHoverEvent
OnRecordDoubleClickEvent AllowFormatinEditMode
AllowSearching
cellEditType
CssName
FormatText
GridCommands
HeaderText
HtmlEncode
IsUnbound
JqueryFormat
maskEditParams
Member
Name
numericEditParams
percentEditParams
ResizeSettings
TemplateColumn
TemplateName
TextAlign
type
Events Arguments
Visible
Width
gridObj.remove_OnActionBegin(OnActionBegin);
gridObj.remove_OnCellEdit(OnCellEdit);
gridObj.remove_OnCellSave(OnCellSave);
gridObj.remove_OnBulkSave(OnBulkSave);
gridObj.remove_OnActionSuccess(OnActionSuccess);
gridObj.remove_onResizingStart(onResizingStart);
gridObj.remove_onResizingEnd(onResizingEnd);
gridObj.remove_Resized(Resized);
gridObj.remove_onDragStart(onDragStart);
gridObj.remove_beforeDrop(beforeDrop);
gridObj.remove_afterDrop(afterDrop);
gridObj.remove_MouseUpDrop(MouseUpDrop);
gridObj.remove_OnToolbarClickEvent(OnToolbarClickEvent);
gridObj.remove_OnRecordExpanding(OnRecordExpanding);
gridObj.remove_OnRecordExpanded(OnRecordExpanded);
gridObj.remove_OnRecordCollapsing(OnRecordCollapsing);
gridObj.remove_OnRecordCollapsed(OnRecordCollapsed);
a. To expand a grouped column details, use the following code in the view page.
gridobj.set_PrimaryKeys(["OrderID","CustomerID","ShipCity"]);
}
</script>
Figure 257: OrderID, CustomerID and ShipCity columns are set as primary key
Figure 260: Selecting the Direction “Right” for the Enter Key
<script type="text/javascript">
Sys.Application.add_load(function () {
var gridObj = $find("OrderGrid");
gridObj.set_tabKey("Down");
})
</script>
<script type="text/javascript">
function selectGridRow() {
var gridobj = $find("OrderGrid");
gridobj.selectRow(0);
}
</script>
b. To cancel the selection of the row, include the following code sample in the view page.
View
<input type="button" onclick="deSelectGridRow()"
value="Deselect Row" />
<script type="text/javascript">
function deSelectGridRow() {
var gridobj = $find("OrderGrid");
gridobj.deselectRow(0);
}
</script>
Figure 264: The second row and first column cell is selected
<script type="text/javascript">
function selectMultipleRows() {
var gridobj = $find("OrderGrid");
gridobj. selectMutipleRows(2,7);
}
</script>
<script type="text/javascript">
function selectGrid() {
var gridobj = $find("OrderGrid");
gridobj.selectAll();
}
</script>
View
<script type="text/javascript">
function hideGridRow() {
var gridobj = $find("OrderGrid");
gridobj.hideRow(0);
}
</script>
View
<input type="button" onclick="showGridRow()" value="Show
Row" />
<script type="text/javascript">
function showGridRow() {
var gridobj = $find("OrderGrid");
gridobj.showRow(0);
}
</script>
4.23.7.2 Column
The column can be hidden in two ways:
By ColumnName
By ColumnIndex
4.23.7.2.1 By ColumnName
You can show or hide columns in a grid by using the showColumn(columnName) and
hideColumn(columnName) methods.
The following code example illustrates how to enable the preceding client-side operation.
a. To show a column, add the following code to the view page:
View
function showGridColumn() {
var gridobj = $find("OrderGrid");
gridobj.showColumn("OrderID");
}
</script>
View
<script type="text/javascript">
function hideGridColumn() {
var gridobj = $find("OrderGrid");
gridobj.hideColumn("OrderID");
}
</script>
4.23.7.2.2 By ColumnIndex
You can show or hide columns in a grid by using the showColumnByIndex(index) and
hideColumnByIndex(index) methods.
The following code example illustrates how to enable the preceding client-side operation.
a. To show a column, add the following code to the view page:
View
function showGridColumn() {
var gridobj = $find("OrderGrid");
gridobj.showColumnByIndex(0);
}
</script>
View
<script type="text/javascript">
function hideGridColumn() {
var gridobj = $find("OrderGrid");
gridobj.hideColumnByIndex(0);
}
</script>
Figure 269: show the “OrderID” of the Grid using showColumnByIndex() and showColumn()
Figure 270: Hide the “OrderID” column using hideColumn() and hideColumnByIndex()
4.23.7.3 GroupDropArea
Show or hide the groupdroparea in a grid by using the set_ ShowGroupDropArea methods.
The following code example illustrates how to enable the preceding client-side
showGroupDropArea operation.
a. To show a GroupDropArea, use the following code in the view page.
View
<script type="text/javascript">
function showGroupDropArea() {
var gridobj = $find("OrderGrid");
gridobj. set_ ShowGroupDropArea(true);
}
</script>
b. To hide a row header, use the following code in the view page.
View
<input type="button" onclick="hideGroupDropArea()" value="Hide
GroupDrop area" />
<script type="text/javascript">
function hideGroupDropArea() {
var gridobj = $find("OrderGrid");
gridobj. set_ ShowGroupDropArea(false);
}
</script>
4.23.7.4 RowHeader
The row header in a grid can be hidden by using the set_ShowRowHeader methods.
The following code example illustrates how to disable the preceding client-side ShowRowHeader
operation.
a. To hide a row header, use the following code in the view page.
View
<input type="button" onclick="hideRowHeader()" value="Hide
RowHeader" />
<script type="text/javascript">
function hideRowHeader() {
var gridobj = $find("OrderGrid");
gridobj.set_ShowRowHeader(false);
}
</script>
View
<script type="text/javascript">
function enableRowHover() {
var gridobj = $find("OrderGrid");
gridobj. set_ EnableRowHover(true);
}
</script>
View
<input type="button" onclick="disableRowHover()"
value="Disable RowHover" />
<script type="text/javascript">
function disableRowHover() {
var gridobj = $find("OrderGrid");
gridobj.set_ EnableRowHover(false);
}
</script>
View
<input type="button" onclick="disableEditing()" value="Disable Editing"
/>
<script type="text/javascript">
function disableEditing () {
var gridobj = $find("OrderGrid");
gridobj.set_ AllowEditing(false);
}
</script>
View
<input type="button" onclick="disableGrouping()" value="Disable
Grouping" />
<script type="text/javascript">
function disableGrouping () {
var gridobj = $find("OrderGrid");
gridobj.set_ AllowGrouping(false);
}
</script>
View
<input type="button" onclick="enablePaging()" value="Enable Paging" />
<script type="text/javascript">
function enablePaging() {
var gridobj = $find("OrderGrid");
gridobj. set_ AllowPaging(true);
}
</script>
View
<input type="button" onclick="disablePaging()" value="Disable Paging"
/>
<script type="text/javascript">
function disablePaging() {
var gridobj = $find("OrderGrid");
gridobj.set_ AllowPaging(false);
}
</script>
View
<input type="button" onclick="enableSelection()" value="Enable
Selection" />
<script type="text/javascript">
function enableSelection() {
var gridobj = $find("OrderGrid");
gridobj. set_ AllowSelection(true);
}
</script>
View
<input type="button" onclick="disableSelection()" value="Disable
Selection" />
<script type="text/javascript">
function disableSelection() {
var gridobj = $find("OrderGrid");
gridobj.set_ AllowSelection(false);
}
</script>
<style type="text/css">
.CustomCell
{
text-align: right;
font-weight: bold;
}
</style>
<script type="text/javascript">
Sys.Application.add_load(function () {
var gridObj = $find("OrderGrid");
gridObj.set_currentCellBackground("CustomCell");
})
</script>
<style type="text/css">
.CustomRowColor
{
background-color: Yellow;
}
</style>
<script type="text/javascript">
Sys.Application.add_load(function () {
var gridObj = $find("OrderGrid");
gridObj.set_selectedAreaBackgroundColorCss("CustomRowColor"
);
})
</script>
<style type="text/css">
.CustomRowHeaderColor
{
background-color: Yellow;
}
</style>
<script type="text/javascript">
Sys.Application.add_load(function () {
var gridObj = $find("OrderGrid");
gridObj.set_rowHeaderSelectionCss("CustomRowHeaderColor ");
})
</script>
Figure 286: Client-Side Custom Formatting for the currently selected row header
font-style : italic;
font-weight : bold;
}
</style>
<script type="text/javascript">
Sys.Application.add_load(function () {
var gridObj = $find("OrderGrid");
gridObj.set_columnHeaderSelectionCss("CustomColumnHeader");
})
</script>
Figure 269: Client-Side Custom Formatting for the Currently Selected Column header
<style type="text/css">
.CustomCloneElement
{
background : yellow;
}
</style>
<script type="text/javascript">
Sys.Application.add_load(function () {
var gridObj = $find("OrderGrid");
gridObj. set_CloneCss("CustomCloneElement");
})
</script>
Figure 287: Client-side custom formatting for the clone element of a dragged column
function sortGrid() {
var gridObj = $find("OrderGrid");
// Client-side sorting using ColumnName, Sort
Direction
gridObj.DoSorting("OrderID", "Descending");
}
</script>
function clearSorting() {
var gridObj = $find("OrderGrid");
// Client-side clear sorting using ColumnName
gridObj. clearSortingforColumn("OrderID");
}
</script>
Figure 272: Before clearing the sorting for the OrderID column
For sending the searching request through the client side, add the following code sample in the
view page.
</script>
}
</script>
Methods
The following code samples illustrate the passing of values between grid actions.
<%=Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.EnableSorting()
.EnablePaging()
.AutoFormat(Skins.Sandune)
.QueryParam("Category= 5")
.Column( columns => {
columns.Add(p => p.OrderID).HeaderText("Order
ID").Width(150);
columns.Add(p => p.CustomerID).HeaderText("Customer
ID").Width(200);
columns.Add(p => p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship Country");
columns.Add(p => p.OrderDate).HeaderText("Order
Date").Format("{0:dd-MM-yyyy}");
})
%>
View [cshtml]
@{ Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.EnableSorting()
.EnablePaging()
.AutoFormat(Skins.Sandune)
.QueryParam("Category= 5")
.Column( columns => {
columns.Add(p => p.OrderID).HeaderText("Order
ID").Width(150);
columns.Add(p => p.CustomerID).HeaderText("Customer
ID").Width(200);
columns.Add(p => p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship Country");
columns.Add(p => p.OrderDate).HeaderText("Order
Date").Format("{0:dd-MM-yyyy}");
}).Render();
}
The value passed in a category is shared among all other grid actions like paging requests,
sorting requests, grouping requests, group expand requests, and filtering requests.
The value passed in category is shared among all other grid actions like paging requests, sorting
requests, grouping requests, group expand requests, and filtering requests.
Templates allow you to customize the way data is presented in the grid. Using template columns,
you can display images, links, and so on. It will give a better look and feel to the data presented in
the grid. It is very simple as the user can directly specify the template for the column.
The user can display customized data inside columns using this feature.
Properties
Property Description Type of Value it accepts Any other
property dependencie
s/sub-
properties
associated
TemplateColumn Gets or sets the Boolean True/False NA
particular column,
indicating if it is a
template column or not.
Sample Link
1. By specifying the name of the template in the property TemplateName of the particular
column.
2. Rendering the template through the UIHint annotation attribute of the particular column. In
this case, set the TemplateColumn property to True. There is no need to set the
TemplateName property as the name of the template is specified through UIHint
annotation attribute of the particular column.
[UIHint("ProductTemplate"), Required]
public string Product
{
get;
set;
View [ASPX]
<%= Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.Column(column =>
{
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p =>
p.Product).HeaderText("Product").TemplateColumn(true);
column.Add(p => p.CustomerID).HeaderText("CustomerId");
})
%>
View [cshtml]
@{ Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.Column(column =>
{
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p =>
p.Product).HeaderText("Product").TemplateColumn(true);
column.Add(p => p.CustomerID).HeaderText("CustomerId");
}).Render();
}
In the code above, the “Product” column will render the template “ProductTemplate”.
1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. In the view, use its Model property in Datasource() to bind the data source.
4. To render the template for the particular column, set its TemplateColumn property to True.
View [ASPX]
<%= Html.Syncfusion().Grid<Employee>("Grid1")
.Datasource(Model)
.Caption("Employees")
.Column(column =>
{
column.Add("Employee").HeaderText("Photo").TemplateColumn(true).Templat
eName("EmployeeTemplate");
column.Add(p =>
p.FirstName).HeaderText("Name");
column.Add(p =>
p.HireDate).HeaderText("HireDate");
column.Add(p =>
p.Address).HeaderText("Address");
})
.EnablePaging()
.PageSettings(p=>p.PageSize(3).PageCount(3).PagerStyle(PagerStyle.PrevN
extAndManual))
.EnableSorting()
.AutoFormat(Skins.Marble)
%>
View [cshtml]
@{ Html.Syncfusion().Grid<Employee>("Grid1")
.Datasource(Model)
.Caption("Employees")
.Column(column =>
{
column.Add("Employee").HeaderText("Photo").TemplateColumn(true).Templat
eName("EmployeeTemplate");
column.Add(p =>
p.FirstName).HeaderText("Name");
column.Add(p =>
p.HireDate).HeaderText("HireDate");
column.Add(p =>
p.Address).HeaderText("Address");
})
.EnablePaging()
.PageSettings(p=>p.PageSize(3).PageCount(3).PagerStyle(PagerStyle.PrevN
extAndManual))
.EnableSorting()
.AutoFormat(Skins.Marble).Render();
202.
“EmployeeTemplate.ascx”
203.
“EmployeeTemplate.cshtml”
<img alt="@Model.FirstName"
src="@Url.Content("/Content/Images/Employees/" + Model.EmployeeID +
".png")" style="width:175px" />
204.
205.
6. Set its data source and render the view.
206.
Controller
/// <summary>
/// Used to bind the Grid.
/// </summary>
/// <returns>View page, it displays the Grid</returns>
public ActionResult Index()
{
var data = new NorthwindDataContext().Employees.ToList();
return View(data);
}
207.
View [ASPX]
<%= Html.Syncfusion().Grid<Employee>("Grid1")
.ActionMode(ActionMode.JSON)
.Caption("Employees")
.Column(column =>
{
column.Add("Employee").HeaderText("Photo").TemplateColumn(true).Templat
eName("EmployeeTemplate");
column.Add(p =>
p.FirstName).HeaderText("Name");
column.Add(p =>
p.HireDate).HeaderText("HireDate");
column.Add(p =>
p.Address).HeaderText("Address");
})
.EnablePaging()
.PageSettings(p=>p.PageSize(3).PageCount(3).PagerStyle(PagerStyle.PrevN
extAndManual))
.EnableSorting()
.AutoFormat(Skins.Marble)
%>
View [cshtml]
@{ Html.Syncfusion().Grid<Employee>("Grid1")
.ActionMode(ActionMode.JSON)
.Caption("Employees")
.Column(column =>
{
column.Add("Employee").HeaderText("Photo").TemplateColumn(true).Templat
eName("EmployeeTemplate");
column.Add(p =>
p.FirstName).HeaderText("Name");
column.Add(p =>
p.HireDate).HeaderText("HireDate");
column.Add(p =>
p.Address).HeaderText("Address");
})
.EnablePaging()
.PageSettings(p=>p.PageSize(3).PageCount(3).PagerStyle(PagerStyle.PrevN
extAndManual))
.EnableSorting()
.AutoFormat(Skins.Marble).Render();
208.
6. Create the template for the “Employee” column.
209.
“EmployeeTemplate.ascx”
210.
“EmployeeTemplate.cshtml”
<img alt="${FirstName}"
src="@Url.Content("~/Content/Images/Employees/${EmployeeID}.png")"
style=width: 175px;" />
In JSON mode, model binding can be done by using the following syntax.
Syntax: ${ColumnName}
Example: ${EmployeeID}
211.
1. Render the view.
Controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new
NorthwindDataContext().Employess.ToList();
return data.GridJSONActions<Employee>();
}
214.
3. Run the application. The grid will appear as shown below.
4.26 Toolbar
Essential Grid provides toolbar support and it can be customized. It contains the following built-in
toolbar items:
AddNew
Delete
Cancel
Edit
Update
Custom
Export
The custom toolbar items can be added by setting the ToolbarOptions ItemType property to
Custom.
Sample Link
1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. Create the Grid control in the view and configure its properties.
4. Set the OnToolbarClickEvent handler for handling the toolbar click events.
View [ASPX]
<%=Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model)
.Caption("Orders")
.Column(column =>
{
column.Add(p =>
p.OrderID).HeaderText("Order ID");
column.Add(p =>
p.CustomerID).HeaderText("Customer ID");
column.Add(p =>
p.EmployeeID).HeaderText("EmployeeID");
column.Add(p =>
p.ShipCountry).HeaderText("ShipCountry");
column.Add(p =>
p.ShipAddress).HeaderText("ShipAddress");
})
.ClientSideEvents(e =>
e.OnToolbarClickEvent("OnToolbarClickEvent"))
.ToolBar(tools =>
{
// Adding the custom toolbar items.
// Add(customItemtitle, customItemcaption,
customItemCssClass)
tools.Add("ExpandAll", "Expand", "ExpandItem")
.Add("CollapseAll", "Collapse", "CollapseItem")
.Add("Refresh", "Refresh", "Refresh");
})
%>
View [cshtml]
@{ Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model)
.Caption("Orders")
.Column(column =>
{
column.Add(p =>
p.OrderID).HeaderText("Order ID");
column.Add(p =>
p.CustomerID).HeaderText("Customer ID");
column.Add(p =>
p.EmployeeID).HeaderText("EmployeeID");
column.Add(p =>
p.ShipCountry).HeaderText("ShipCountry");
column.Add(p =>
p.ShipAddress).HeaderText("ShipAddress");
})
.ClientSideEvents(e =>
e.OnToolbarClickEvent("OnToolbarClickEvent"))
.ToolBar(tools =>
{
// Adding the custom toolbar items.
// Add(customItemtitle, customItemcaption, customItemCssClass)
tools.Add("ExpandAll", "Expand", "ExpandItem")
.Add("CollapseAll", "Collapse", "CollapseItem")
.Add("Refresh", "Refresh", "Refresh");
})
.Render();
}
<script type="text/javascript">
216.
6. Render the view.
Controller
218. Create a model in the application (Refer to How to>Adding a Model to the Application).
219. Create a strongly typed view (Refer to How to>Strongly Typed View)
3. Add the following code in the Index.aspx file to create the Grid control in the view.
220.
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("Grid1", column=>
{
column.Add(p =>
p.OrderID).HeaderText("OrderID");
column.Add(p =>
p.CustomerID).HeaderText("CustomerID");
column.Add(p => p.
EmployeeID).HeaderText("EmployeeID");
column.Add(p =>
p.ShipAddress).HeaderText("ShipAddress");
column.Add(p =>
p.ShipCountry).HeaderText("ShipCountry");
}));
%>
View [cshtml]
@( Html.Syncfusion().Grid<Order>("Grid1", column=>
{
column.Add(p => p.OrderID).HeaderText("OrderID");
column.Add(p => p.CustomerID).HeaderText("CustomerID");
column.Add(p => p.EmployeeID).HeaderText("EmployeeID");
column.Add(p => p.ShipAddress).HeaderText("ShipAddress");
column.Add(p => p.ShipCountry).HeaderText("ShipCountry");
})
)
221.
4. Create a GridPropertiesModel in the Index method and assign the grid properties in the
model. Set the OnToolbarClickEvent to handle the toolbar click event.
222.
Controller
Caption = "Orders",
AllowPaging=true,
AllowSorting=true,
AllowGrouping=true,
AutoFormat = Skins.Sandune
};
model.ClientSideEvents.OnToolbarClickEvent =
"OnToolbarClickEvent";
ViewData["Grid1"] = model;
223.
5. To add custom toolbar items, configure the toolbar as given in the following code sample.
224.
Controller
toolbar.Enable = true;
model.ToolBar = toolbar;
225.
6. Handle the OnToolbarClickEvent as shown below.
226.
<script type="text/javascript">
227.
GridToolBarItems.Ed
it
GridToolBarItems.Up
date
GridToolBarItems.Cu
stom
GridToolBarItems.Ex
port
Mapper Gets or sets the mapper List<ToolbarOpti Any toolbar items ItemType
for the toolbar item when ons>
the ItemType is set to
Export
4.26.4 Methods
The following table provides the methods of the ToolbarOptions class.
4.26.5 Events
The following table provides the events of the ToolbarOptions class.
_disabled specifies
whether the current
clicked toolbar item is
disabled or not.
_itemType specifies
whether the current
clicked toolbar item is
a built-in item or
custom item.
4.27 MultiColumnDropDown
In the figure above, a student can see all the university course details like course fees, duration,
CGPA, course code, etc. But after selecting one, it is not necessary to show all the details.You
can simply display the Univerity Code, fees, and CGPA.
Key Features
1. Bind the data source directly to the control; it will generate columns accordingly. No further
steps are required.
2. The MultiColumnDropdown control has some predefined skins which can be controlled
through a single property setting.
The following image marks the important sections of the MultiColumnDropDown control.
To know how to create an ASP.NET MVC application and add Essential Grid to the application,
refer to the Getting Started section.
This section guides you on creating a multicolumn drop-down which includes the following steps.
1. Create a MultiColumnDropDown control in the view and set the data source using the
Datasource() method.
228.
View [ASPX]
<%=Html.Syncfusion().MultiColumnDropDown<Student>("MultiColumnDropdown"
)
.Datasource((IEnumerable) ViewData["data"])
.DisplayExpression(new int[] {2, 3, 5})
.Width(500)
.Text("--Select--")
%>
229.
230.
View [cshtml]
@(
Html.Syncfusion().MultiColumnDropDown<Student>("MultiColumnDropdown")
.Datasource((IEnumerable) ViewData["data"])
.DisplayExpression(new int[] {2, 3, 5})
.Width(500)
.Text("--Select--")
)
Controller
/// <summary>
/// Used for rendering the multicolumn drop-down
initially.
/// </summary>
/// <returns>View page; it displays the multicolumn drop-
down.</returns>
public ActionResult Index()
{
ViewData["data"] = new
StudentDataContext().JSONStudent.Skip(0).Take(30).ToList();
return View();
}
3. Run the application. The multicolumn drop-down will appear as shown below.
A sample that demonstrates a basic MultiColumnDropdown control can be downloaded from the
following link:
http://help.syncfusion.com/Support/grid_mvc/v8.3.0.20/UG/MvcMultiColumnDropdownSample.zip
Note: The version number for the assemblies has been set to 8.3.0.20 in the Web.config file of
the attached sample. Please change the version number to the appropriate version in the Web-
2008.config or Web-2010.config files (available in root directory) and those will automatically be
updated in the Web.config file.
Methods
In order to work with this feature please follow the steps below.
1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. In the view create the MultiColumnDropDown control and specify the data source using the
Datasource() method.
View [ASPX]
<%=Html.Syncfusion().MultiColumnDropDown<Student>("MultiCol
umnDropdown")
.Datasource((IEnumerable) ViewData["data"])
.Width(500)
.Text("--Select--")
%>
231.
View [cshtml]
@{
Html.Syncfusion().MultiColumnDropDown<Student>("MultiColumnDropdown")
.Datasource((IEnumerable) ViewData["data"])
.Width(500)
.Text("--Select--")
.Render();
}
2. Specify the display column indexes in array format using the DisplayExpression() method.
232.
View [ASPX]
<%=Html.Syncfusion().MultiColumnDropDown<Student>("MultiColumnDro
pdown")
.Datasource((IEnumerable) ViewData["data"])
.DisplayExpression(new int[] {2, 3, 5})
.Width(500)
.AutoFormat(Skins.Office2007Black)
.Text("--Select--")
%>
View [cshtml]
@( Html.Syncfusion().MultiColumnDropDown<Student>("MultiColumnDropdown")
.Datasource((IEnumerable) ViewData["data"])
.DisplayExpression(new int[] {2, 3, 5})
.Width(500)
.AutoFormat(Skins.Office2007Black)
.Text("--Select--")
)
1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create the MultiColumnDropdown control in the view.
View [ASPX]
<%=Html.Syncfusion().MultiColumnDropDown<Student>("Multidropdown",(Mult
View [cshtml]
@(
Html.Syncfusion().MultiColumnDropDown<Student>("Multidropdown",(MultiCo
lumnDropDownModel) ViewData["dropdown"]))
4. Specify the display column indexes in array format using the DisplayExpression property.
4.27.3.2 Appearance
The MultiColumnDropDown control supports fifteen professional built-in skins. These skins can
be applied to the drop-down column to enhance the look and feel of the control.
Office 2007Blue
Office 2007Black
Office 2007Silver
Vista
Almond
Blend
Blueberry
Marble
Metro
Midnight
Monochrome
Olive
Sandune
Turquoise
Property
Skins.Almond
Skins.Blend
Skins.Blueberry
Skins.Marble
Skins.Metro
Skins.Midnight
Skins.Monochrome
Skins.Olive
Skins.Sandune
Skins.Turquoise
Skins.VS2010
Methods
Sample Link
To access the sample link:
233. Go to Tools MVC Demos in the sample browser. Refer to Installation and
Deployment>Samples and Location.
234.
235. Select the Multi Column Drop-Down item in the demo list.
236.
3. Select any of the demos to view the MultiColumnDropDown full-fledged demo.
Skins can be applied to the MultiColumnDropDown control in two ways.
Through Builder
Through MultiColumnDropDownModel
In order to work with this feature please follow the steps below.
1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. In the view, create the MultiColumnDropDown control and configure its properties.
View [ASPX]
<%=Html.Syncfusion().MultiColumnDropDown<Student>("MultiColumnDro
pDown")
.Datasource((IEnumerable) ViewData["data"])
.DisplayExpression(new int[] {2, 3, 5})
.Width(500)
.Text("--Select--")
%>
View [cshtml]
@( Html.Syncfusion().MultiColumnDropDown<Student>("MultiColumnDropDown")
.Datasource((IEnumerable) ViewData["data"])
.DisplayExpression(new int[] {2, 3, 5})
.Width(500)
.Text("--Select--")
View [ASPX]
<%=Html.Syncfusion().MultiColumnDropDown<Student>("MultiColumnDropDown"
)
.Datasource((IEnumerable) ViewData["data"])
.DisplayExpression(new int[] {2, 3, 5})
.Width(500)
.AutoFormat(Skins.Sandune)
.Text("--Select--")
%>
View [cshtml]
@( Html.Syncfusion().MultiColumnDropDown<Student>("MultiColumnDropDown")
.Datasource((IEnumerable) ViewData["data"])
.DisplayExpression(new int[] {2, 3, 5})
.Width(500)
.AutoFormat(Skins.Sandune)
.Text("--Select--")
)
1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create MultiColumnDropdown control in the view.
View [ASPX]
<%=Html.Syncfusion().MultiColumnDropDown<Student>("Multidropdown",(Mult
iColumnDropDownModel) ViewData["dropdown"]) %>
View [cshtml]
@(
Html.Syncfusion().MultiColumnDropDown<Student>("Multidropdown",(MultiCo
lumnDropDownModel) ViewData["dropdown"]))
Controller
Controller
4.27.3.3 RightToLeft
The MultiColumnDropDown control now supports a full-fledged right-to-left mode which aligns
content in the control from right to left.
Use Case Scenarios
The RightToLeft property is used for international applications where the language is written
from right to left, such as Hebrew or Arabic. When this property is set to True, the
MultiColumnDropDown control will be displayed from right to left.
MultiColumnDropDownModel
View [ASPX]
<%=Html.Syncfusion().MultiColumnDropDown<Student>("MultiColumnDro
pDown")
.Datasource((IEnumerable) ViewData["data"])
.DisplayExpression(new int[] {2, 3, 5})
.Width(500)
.Text("--Select--")
%>
View [cshtml]
@( Html.Syncfusion().MultiColumnDropDown<Student>("MultiColumnDropDown")
.Datasource((IEnumerable) ViewData["data"])
.DisplayExpression(new int[] {2, 3, 5})
.Width(500)
.Text("--Select--")
)
View [ASPX]
<%=Html.Syncfusion().MultiColumnDropDown<Student>("MultiColumnDropDown"
)
.Datasource((IEnumerable) ViewData["data"])
.DisplayExpression(new int[] {2, 3, 5})
.Width(500)
.RightToLeft(true)
.Text("--Select--")
%>
View [cshtml]
@( Html.Syncfusion().MultiColumnDropDown<Student>("MultiColumnDropDown")
.Datasource((IEnumerable) ViewData["data"])
.DisplayExpression(new int[] {2, 3, 5})
.Width(500)
.RightToLeft(true)
.Text("--Select--")
)
Controller
/// <summary>
/// Used for rendering the MultiColumnDropDown initially.
/// </summary>
/// <returns>View page; it displays the
MultiColumnDropDown.</returns>
public ActionResult Index()
{
View [ASPX]
<%=Html.Syncfusion().MultiColumnDropDown<Student>("Multidropdown",(Mult
iColumnDropDownModel) ViewData["dropdown"]) %>
View [cshtml]
@(
Html.Syncfusion().MultiColumnDropDown<Student>("Multidropdown",(MultiCo
lumnDropDownModel) ViewData["dropdown"]))
Controller
// Create instance to MultiColumnDropDown model and assign properties.
MultiColumnDropDownModel dropdown = new
MultiColumnDropDownModel()
{
Datasource = new
StudentDataContext().JSONStudent.Skip(0).Take(30).ToList(),
Text = "--Select--",
DisplayExpression = new int[3] { 2, 3, 5 },
Width = 500
};
Controller
Controller
// Pass the MultiColumnDropDownModel to view using ViewData()
ViewData["dropdown"] = dropdown;
In the Mozilla browser, the side the scroll bar appears on can be configured in right-to-left (RTL)
and left-to-right (LTR) modes. The following are the options to configure ScrollbarSide.
Presently, the MultiColumnDropDown control supports both sides of the scrollbar in RTL mode
using the MozillaLayoutScrollbarSide property.
The following steps are necessary to configure the scroll bar side in the Mozilla browser.
1. Type the URL about:config in the Mozilla browser and press ENTER to configure the
settings of the Mozilla browser.
2. Type layout.scrollbar in the Filter: text box and set the value to 1. The default value is 0.
Properties
Methods
Sample Link
To access the sample link:
1. Go to Tools MVC Demos in the sample browser. Refer to Installation and
Deployment>Samples and Location.
2. Select the Multi Column Drop-Down on the left side Accordion.
3. Select any of the demos to view the MultiColumnDropDown full demo.
Methods
239.
View [ASPX]
<%=Html.Syncfusion().MultiColumnDropDown<Student>("MultiColumnDropdown"
)
.Datasource((IEnumerable) ViewData["data"])
.DisplayExpression(new int[] {2, 3, 5})
.Width(500)
.Text("--Select--")
%>
View [cshtml]
@(
Html.Syncfusion().MultiColumnDropDown<Student>("MultiColumnDropdown")
.Datasource((IEnumerable) ViewData["data"])
.DisplayExpression(new int[] {2, 3, 5})
.Width(500)
.Text("--Select--")
)
View [cshtml]
@(
Html.Syncfusion().MultiColumnDropDown<Student>("MultiColumnDropdo
wn")
.Datasource((IEnumerable) ViewData["data"])
.DisplayExpression(new int[] {2, 3, 5})
.Width(500)
.AutoFormat(Skins.Office2007Black)
.PopupDirection(GenericDropDownPopupDirection.Up)
.Text("--Select--")
)
241. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create the MultiColumnDropDown control in the view.
242.
View [ASPX]
<%=Html.Syncfusion().MultiColumnDropDown<Student>("Multidropdown",(Mult
iColumnDropDownModel) ViewData["dropdown"]) %>
View [cshtml]
@(
Html.Syncfusion().MultiColumnDropDown<Student>("Multidropdown",(MultiCo
lumnDropDownModel) ViewData["dropdown"]))
Width = 500
};
Methods
Method Parameters Return type Descriptions
InitiallyPopupShown(bool) bool IMultiColumnDropDownBuilder When set to True,
it displays the pop
up panel on page
load.
<%=Html.Syncfusion().MultiColumnDropDown<Student>("MultiCol
umnDropdown")
.Datasource((IEnumerable) ViewData["data"])
View [cshtml]
@(
Html.Syncfusion().MultiColumnDropDown<Student>("MultiColumnDropdown")
.Datasource((IEnumerable) ViewData["data"])
.DisplayExpression(new int[] {2, 3, 5})
.Width(500)
.Text("--Select--")
)
View [cshtml]
@(
Html.Syncfusion().MultiColumnDropDown<Student>("MultiColumn
Dropdown")
.Datasource((IEnumerable) ViewData["data"])
.DisplayExpression(new int[] {2, 3, 5})
.Width(500)
.AutoFormat(Skins.Office2007Black)
.InitiallyPopupShown(true)
)
4. Specify the default text box value using the Text() method.
248.
View [Aspx]
<%=Html.Syncfusion().MultiColumnDropDown<Student>("MultiColumnDropdo
wn")
.Datasource((IEnumerable) ViewData["data"])
.DisplayExpression(new int[] {2, 3, 5})
.Width(500)
.AutoFormat(Skins.Office2007Black)
.Text("--Select--")
.InitiallyPopupShown(true)
%>
View [cshtml]
@(
Html.Syncfusion().MultiColumnDropDown<Student>("MultiColumnDropdown"
)
.Datasource((IEnumerable) ViewData["data"])
.DisplayExpression(new int[] {2, 3, 5})
.Width(500)
.AutoFormat(Skins.Office2007Black)
.Text("--Select--")
.InitiallyPopupShown(true))
5. Run the application. The multicolumn pop-up panel will open on page load and will appear
as shown below.
1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create the MultiColumnDropDown control in the view.
249.
View [ASPX]
<%=Html.Syncfusion().MultiColumnDropDown<Student>("Multidropdown",(Mult
iColumnDropDownModel) ViewData["dropdown"]) %>
View [cshtml]
@(
Html.Syncfusion().MultiColumnDropDown<Student>("Multidropdown",(MultiCo
lumnDropDownModel) ViewData["dropdown"]))
4. To display the pop-up panel when the page loads, use the InitiallyPopupShown property.
251.
// Create instance to MultiColumnDropDownModel and assign
properties.
MultiColumnDropDownModel dropdown = new
MultiColumnDropDownModel()
{
Datasource = new
StudentDataContext().JSONStudent.Skip(0).Take(30).ToList(),
DisplayExpression = new int[3] { 2, 3, 5 },
Width = 500,
AutoFormat = Skins.Office2007Black,
InitiallyPopupShown=true
};
5. Specify the default text box value by using the Text property.
252.
// Create instance to MultiColumnDropDownModel and assign
properties.
MultiColumnDropDownModel dropdown = new
MultiColumnDropDownModel()
{
Datasource = new
StudentDataContext().JSONStudent.Skip(0).Take(30).ToList(),
Text = "--Select--",
DisplayExpression = new int[3] { 2, 3, 5 },
Width = 500,
AutoFormat = Skins.Office2007Black,
InitiallyPopupShown=true
};
7. Run the application. The multicolumn pop-up panel will open when the page loads and will
appear as shown below.
<%=Html.Syncfusion().MultiColumnDropDown<Student>("MultiColumnDro
pDown")
.Datasource(Model)
.DisplayExpression(new int[] { 0,1,3 })
.AllowSorting(true)
.Columns(col => {
col.Add(m =>
m.UniversityCode).HeaderText(“UnivCode”);
col.Add(m => m.Title).Width(150);
col.Add(m =>
m.CourseFees).AllowSorting(false);
col.Add(m => m.CGPA);
})
%>
View [cshtml]
@(
Html.Syncfusion().MultiColumnDropDown<Student>("MultiColumnDropDo
wn")
.Datasource(Model)
.DisplayExpression(new int[] { 0,1,3 })
.AllowSorting(true)
.Columns(col => {
col.Add(m =>
m.UniversityCode).HeaderText(“UnivCode”);
col.Add(m => m.Title).Width(150);
col.Add(m =>
m.CourseFees).AllowSorting(false);
col.Add(m => m.CGPA);
})
)
Controller
/// <summary>
/// Used for rendering the MultiColumnDropDown initially.
/// </summary>
/// <returns>View page; it displays the
MultiColumnDropDown.</returns>
public ActionResult Index()
{
6. In order to work with sorting actions, create a Post method for Index actions and bind the
data source to the grid as shown in the following code sample.
Controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
7. Run the application. The MultiColumnDropDown will appear as shown in the following
screenshot.
Figure 314: MultiColumnDropDown with HeaderText “UnivCode” and the Width of the Title Column Set to
150px
1. Create a model in the application. Refer to How to>Adding a Model to the Application.
2. Add the following code in the Index.aspx file to create the MultiColumnDropDown
control in the view.
View [ASPX]
<%=
Html.Syncfusion().MultiColumnDropDown<MvcSampleApplication.Models.Stude
nt>("MulticolumnControl1", "DropDownModel", col =>
{
col.Add(m => m.UniversityCode).HeaderText("UnivCode");
col.Add(m => m.Title).Width(150);
col.Add(m => m.CourseFees).AllowSorting(false);
col.Add(m => m.CGPA);
})%>
View [cshtml]
@(
Html.Syncfusion().MultiColumnDropDown<MvcSampleApplication.Models.Stude
nt>("MulticolumnControl1", "DropDownModel", col =>
{
col.Add(m => m.UniversityCode).HeaderText("UnivCode");
col.Add(m => m.Title).Width(150);
col.Add(m => m.CourseFees).AllowSorting(false);
col.Add(m => m.CGPA);
})
)
Controller
AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(MultiColumnDropDownModel<Student>
dropdown)
{
dropdown.DataSource = new
StudentDataContext().AutoFormatStudent.Take(30);
dropdown.DisplayExpression = new int[2] { 2, 3 };
ViewData["DropDownModel"] = dropdown;
return PartialView("MultiColumnDropDownPartialView");
}
5. In order to work with sorting actions, create a Post method for Index actions and bind the
data source to MultiColumnDropDown as shown in the following code.
Controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index (PagingParams args)
{
IEnumerable data =new
StudentDataContext().AutoFormatStudent.Take(20);
return data.GridActions<Student>();
}
6. Run the application. The MultiColumnDropDown control will appear as shown in the
following screenshot.
Figure 315: MultiColumnDropDown with HeaderText “UnivCode” and Width of Title Column set to 150px
Properties
Sample Link
To access the samples:
1. Go to Tools MVC Demos in the sample browser. Refer to Installation and
Deployment>Samples and Location.
254.
2. Select the Multi Column Drop-Down on the left side Accordion.
255.
3. Select any of the demos to view the MultiColumnDropDown full-fledged demo.
event to control.
Methods
Events
get_SelectedValue() //
Contains the selected value.
_SelectedRow // Returns the
Selected record object
(JSON).
_DisplayValue // Returns the
display value.
_SelectedValue // Returns the
selected Value.
get_SelectedValue() //
Contains the selected value.
_SelectedRow // Returns the
Selected record object
(JSON).
_DisplayValue // Returns the
display value.
(JSON).
get_DisplayValue() // Contains
the display value.
get_SelectedValue() //
Contains the selected value.
_SelectedRow // Returns the
Selected record object
(JSON).
_DisplayValue // Returns the
display value.
_SelectedValue // Returns the
selected Value.
<%=Html.Syncfusion().MultiColumnDropDown<Student>("MultiColumnDropdown"
)
.Datasource((IEnumerable) ViewData["data"])
.DisplayExpression(new int[] {2, 3, 5})
.Width(500)
.AutoFormat(Skins.Office2007Black)
.Text("--Select--")
.ClientSideOnBeforePopupShown("OnBeforePopup")
.ClientSideOnPopupHidden("popupHidden")
.ClientSideOnPopupShown("popupShown")
.ClientSideOnSelect("onRecordSelect")
.ClientSideOnTextChanged("onTextChanged")
%>
View [cshtml]
@( Html.Syncfusion().MultiColumnDropDown<Student>("MultiColumnDropdown")
.Datasource((IEnumerable) ViewData["data"])
.DisplayExpression(new int[] {2, 3, 5})
.Width(500)
.AutoFormat(Skins.Office2007Black)
.Text("--Select--")
.ClientSideOnBeforePopupShown("OnBeforePopup")
.ClientSideOnPopupHidden("popupHidden")
.ClientSideOnPopupShown("popupShown")
.ClientSideOnSelect("onRecordSelect")
.ClientSideOnTextChanged("onTextChanged")
)
[JavaScript]
<script type="text/javascript">
[JavaScript]
<script type="text/javascript">
Include the following code sample in the view page to set the text in a multicolumn drop-down text
box.
View[ASPX]
<script type="text/javascript">
$("#setText").bind('click', function () {
var multiDD = $find("MultiColumnDropdown");
multiDD.setText($('#SetDropDowntext').val());
});
</script>
Include the following code sample in the view to get the old text and show/hide the pop-up panel.
<script type="text/javascript">
$("#setText").bind('click', function () {
var multiDD = $find("MultiColumnDropdown");
multiDD.setText($('#SetDropDowntext').val());
});
function GetOldText() {
var oldText =
$find("MultiColumnDropdown").getOldText();
}
function ShowPopupPanel() {
$find("MultiColumnDropdown").showPopup();
}
function HidePopupPanel() {
$find("MultiColumnDropdown").hidePopup();
}
</script>
4.27.3.9 Sorting
Sorting is defined as the process of arranging items/records in some ordered sequence. Essential
Grid supports arranging table data in ascending ( ) or descending ( ) order based on the
column header that is clicked. The order switches between ascending and descending when you
click a column header for sorting.
Use Case Scenarios
Sorting is used to sort records either by ascending and descending order or by data that can be
retrieved easily.
<%=Html.Syncfusion().MultiColumnDropDown<Student>("MultiColumnDropDown"
)
.Datasource((IEnumerable) ViewData["data"])
.DisplayExpression(new int[] {2, 3, 5})
.Width(500)
.Text("--Select--")
%>
View [cshtml]
@( Html.Syncfusion().MultiColumnDropDown<Student>("MultiColumnDropDown")
.Datasource((IEnumerable) ViewData["data"])
View[Aspx]
<%=Html.Syncfusion().MultiColumnDropDown<Student>("MultiColumnDropDown"
)
.Datasource((IEnumerable) ViewData["data"])
.DisplayExpression(new int[] {2, 3, 5})
.Width(500)
.AllowSorting(true)
.Text("--Select--")
%>
View [cshtml]
@( Html.Syncfusion().MultiColumnDropDown<Student>("MultiColumnDropDown")
.Datasource((IEnumerable) ViewData["data"])
.DisplayExpression(new int[] {2, 3, 5})
.Width(500)
.AllowSorting(true)
.Text("--Select--")
)
Controller
/// <summary>
/// Used for rendering the MultiColumnDropDown initially.
/// </summary>
/// <returns>View page; it displays the
MultiColumnDropDown.</returns>
public ActionResult Index()
{
5. In order to work with sorting actions, create a Post method for Index actions and bind the
data source to MultiColumnDropDown as shown in the following code.
Controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index (PagingParams args)
{
IEnumerable data =new
StudentDataContext().AutoFormatStudent.Take(20);
return data.GridActions<Student>();
}
6. Run the application. The MultiColumnDropDown will appear as shown in the following
screenshot.
View[Aspx]
<%=Html.Syncfusion().MultiColumnDropDown<Student>("Multidropdown",(Mult
iColumnDropDownModel) ViewData["dropdown"]) %>
View [cshtml]
@(
Html.Syncfusion().MultiColumnDropDown<Student>("Multidropdown",(MultiCo
lumnDropDownModel) ViewData["dropdown"]))
Controller
Controller
Controller
// Pass the MultiColumnDropDownModel to the view using ViewData()
ViewData["dropdown"] = dropdown;
259. In order to work with sorting actions, create a Post method for Index actions and bind the
data source to MultiColumnDropDown as shown in the following code sample.
Controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index (PagingParams args)
{
IEnumerable data =new
StudentDataContext().AutoFormatStudent.Take(20);
return data.GridActions<Student>();
}
260. Run the application. The MultiColumnDropDown control will appear as shown below.
The JSON mode of sorting renders records on the server side with all the rendering parts
processed on the client side using MicrosoftAjaxTemplate.
[Site.Master]
<head runat="server">
<script src="<%= Url.Content("~/Scripts/Templates/MicrosoftAjax.js")
%>" type="text/javascript"></script>
<script src="<%=
Url.Content("~/Scripts/Templates/MicrosoftAjaxTemplates.js") %>"
type="text/javascript"></script>
</head>
[_Layout.cshtml]
<head runat="server">
<script src="@Url.Content("~/Scripts/Templates/MicrosoftAjax.js")"
type="text/javascript"></script>
<script
src="@Url.Content("~/Scripts/Templates/MicrosoftAjaxTemplates.js")"
type="text/javascript"></script>
</head>
3. Create a row template for rendering the records’ rows and setting its CSS display
property as none.
View[ASPX]
<table>
<tr id="RowTemplate" style="visibility: hidden;
display: none">
<td class="RowHeader">
</td>
<td class="RowCell">
{{OrderID}}
</td>
<td class="RowCell">
{{CustomerID}}
</td>
<td class="RowCell">
{{EmployeeID}}
</td>
<td class="RowCell">
{{ShipCountry}}
</td>
<td class="RowCell">
{{ShipCity}}
</td>
</tr>
</table>
4. In the view, create the MultiColumnDropDown control and configure its properties.
View [ASPX]
<%=Html.Syncfusion().MultiColumnDropDown<Student>("MultiColumnDro
pDown")
.Datasource((IEnumerable) ViewData["data"])
.DisplayExpression(new int[] {2, 3, 5})
.Width(500)
.Text("--Select--")
%>
View [cshtml]
@(
Html.Syncfusion().MultiColumnDropDown<Student>("MultiColumnDropDo
wn")
.Datasource((IEnumerable) ViewData["data"])
.DisplayExpression(new int[] {2, 3, 5})
.Width(500)
.Text("--Select--"))
5. Enable/disable the sorting feature using the AllowSorting() method, set the JSON mode
using ActionMode, and set the ItemTemplateID using ItemTemplate.
View [ASPX]
<%=Html.Syncfusion().MultiColumnDropDown<Student>("MultiColumnDropDown"
)
.Datasource((IEnumerable) ViewData["data"])
.DisplayExpression(new int[] {2, 3, 5})
.Width(500)
.AllowSorting(true)
.ActionMode("JSON")
.ItemTemplate("RowTemplate")
.Text("--Select--")
%>
View [cshtml]
@( Html.Syncfusion().MultiColumnDropDown<Student>("MultiColumnDropDown")
.Datasource((IEnumerable) ViewData["data"])
.DisplayExpression(new int[] {2, 3, 5})
.Width(500)
.AllowSorting(true)
.ActionMode("JSON")
.ItemTemplate("RowTemplate")
.Text("--Select--"))
Controller
/// <summary>
/// Used to get the JSON Order from Northwind Datacontext
/// </summary>
Controller
/// <summary>
/// Used for rendering the MultiColumnDropDown initially.
/// </summary>
/// <returns>View page, it displays the
MultiColumnDropDown</returns>
public ActionResult Index()
{
For example, when the user tries to sort the column by clicking on the column header, the request
will be sent to the controller from the UI (view).
7. The controller gets the JSON sorting request and prepares a query for processing. The
sorting request is processed by Index HttpPost method. The required data is fetched
according to the query from the database and the response is sent to the view which is
illustrated in the following code.
Controller
/// <summary>
/// Sorting request is mapped to this method.
/// </summary>
/// <returns>JSON data is returned.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IOrderedEnumerable<MvcSampleApplication.Models.JSONOrder>
orderedQuery = null;
// Apply sorting to data source.
if (args.SortDescriptors != null)
{
for (int i = 0; i < args.SortDescriptors.Count;
i++)
{
var sortColumnName =
args.SortDescriptors[i].ColumnName;
if (i == 0)
{
if (args.SortDescriptors[i].SortDirection
== ListSortDirection.Ascending)
{
orderedQuery = ds.OrderBy(c =>
c.Field(sortColumnName));
}
else if
(args.SortDescriptors[i].SortDirection ==
ListSortDirection.Descending)
{
orderedQuery = ds.OrderByDescending(c
=> c.Field(sortColumnName));
}
}
else
{
if (args.SortDescriptors[i].SortDirection
== ListSortDirection.Ascending)
{
orderedQuery = orderedQuery.ThenBy(c
=> c.Field(sortColumnName));
}
else if
(args.SortDescriptors[i].SortDirection ==
ListSortDirection.Descending)
{
orderedQuery =
orderedQuery.ThenByDescending(c => c.Field(sortColumnName));
}
}
}
}
data = orderedQuery;
return Json(data);
}
8. Run the application. The MultiColumnDropDown control will appear as shown in the
following screenshot.
[Master Page]
<head runat="server">
<script src="<%=
Url.Content("~/Scripts/Templates/MicrosoftAjax.js") %>"
type="text/javascript"></script>
<script src="<%=
Url.Content("~/Scripts/Templates/MicrosoftAjaxTemplates.js") %>"
type="text/javascript"></script>
</head>
[_Layout.cshtml]
<head runat="server">
<script src="@Url.Content("~/Scripts/Templates/MicrosoftAjax.js")"
type="text/javascript"></script>
<script
src="@Url.Content("~/Scripts/Templates/MicrosoftAjaxTemplates.js")"
type="text/javascript"></script>
</head>
3. Create a row template for rendering the records’ rows and set its CSS display property
as none.
View[ASPX]
<table>
<tr id="RowTemplate" style="visibility: hidden;
display: none">
<td class="RowHeader">
</td>
<td class="RowCell">
{{OrderID}}
</td>
<td class="RowCell">
{{CustomerID}}
</td>
<td class="RowCell">
{{EmployeeID}}
</td>
<td class="RowCell">
{{ShipCountry}}
</td>
<td class="RowCell">
{{ShipCity}}
</td>
</tr>
</table>
4. In the view, create the MultiColumnDropDown control and configure its properties.
View [ASPX]
<%=Html.Syncfusion().MultiColumnDropDown<Student>("Multidropdown",(Mult
iColumnDropDownModel) ViewData["dropdown"]) %>
View [cshtml]
@(
Html.Syncfusion().MultiColumnDropDown<Student>("Multidropdown",(MultiCo
lumnDropDownModel) ViewData["dropdown"]))
5. Set its data source, configure the properties and render the View.
Controller
/// <summary>
/// Used to get the JSONOrder from Northwind Datacontext
/// </summary>
private IList<JSONOrder> Student
{
get
{
List<JSONOrder> result = (from o in new
StudentDataContext().AutoFormatStudent select new JSONOrder {
6. Enable/disable the sorting feature using the AllowSorting() method, set the JSON mode
using ActionMode, and set the ItemTemplateID using ItemTemplate.
Controller
// Create instance to MultiColumnDropDownModel and assign properties.
MultiColumnDropDownModel dropdown = new
MultiColumnDropDownModel()
{
Datasource = this.Student;
Text = "--Select--",
DisplayExpression = new int[3] { 2, 3, 5 },
Width = 500,
AllowSorting = true,
ActionMode = "JSON",
ItemTemplate = "RowTemplate"
};
For example, when the user tries to sort the column by clicking on the column header this request
will be sent to the controller from the user interface (view).
7. The controller gets the JSON sorting request, and prepares a query for processing. This
sorting request is processed by Index HttpPost method. The required data is fetched
according to the query, from the database and the response is sent to the view, which is
illustrated in the following code.
Controller
/// <summary>
///Sorting request is mapped to this method.
/// </summary>
/// <returns>JSON data is returned.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IOrderedEnumerable<MvcSampleApplication.Models.JSONOrder>
orderedQuery = null;
// Apply sorting to data source.
if (args.SortDescriptors != null)
{
for (int i = 0; i < args.SortDescriptors.Count;
i++)
{
var sortColumnName =
args.SortDescriptors[i].ColumnName;
if (i == 0)
{
if (args.SortDescriptors[i].SortDirection
== ListSortDirection.Ascending)
{
orderedQuery = ds.OrderBy(c =>
c.Field(sortColumnName));
}
else if
(args.SortDescriptors[i].SortDirection ==
ListSortDirection.Descending)
{
orderedQuery = ds.OrderByDescending(c
=> c.Field(sortColumnName));
}
}
else
{
if (args.SortDescriptors[i].SortDirection
== ListSortDirection.Ascending)
{
orderedQuery = orderedQuery.ThenBy(c
=> c.Field(sortColumnName));
}
else if
(args.SortDescriptors[i].SortDirection ==
ListSortDirection.Descending)
{
orderedQuery =
orderedQuery.ThenByDescending(c => c.Field(sortColumnName));
}
}
}
}
data = orderedQuery;
return Json(data);
}
8. Run the application. The MultiColumnDropDown control will appear as shown below.
property b-properties
associated
Methods
Sample Link
To access the samples:
1. Go to Tools MVC Demos in the sample browser. Refer to Installation and Deployment >
Samples and Location.
2. Select the Multi Column Drop-Down on the left side Accordion.
3. Select any of the demos to view the full-fledged MultiColumnDropDown demo.
Drop-down list filters hold the possible values to be filtered of the particular column in the
MultiColumnDropDown control.
You can open menu and submenu items by clicking on the filter icon in the advanced filters
option.
Feature Summary
When the filter feature is enabled in the MultiColumnDropDown control, you can filter data from
multiple columns at the same time so that the data filtered is specific to your need.
Clicking the filter icon opens up a menu of fields that can be filtered out.
When selecting a submenu item, a separate dialog box opens and displays an advanced filter
drop-down that lists the available filter operators for the corresponding column and provides text
boxes. You can type a string to filter out whatever you require to be filtered from the table.
3. Select any sample from the Filtering tab under Multicolumn DropDown and browse
through the features.
Enables the
Filtering feature.
AllowFiltering bool True/false NA
Default value is
False.
Methods
These are the methods used to implement filtering under the MultiColumnDropDown control:
<%=Html.Syncfusion().MultiColumnDropDown<Student>("MultiColumnDropDown"
)
.Datasource((IEnumerable) ViewData["data"])
.DisplayExpression(new int[] {2, 3, 5})
.Width(500)
.AllowFiltering(true)
.Text("--Select--")
%>
View[cshtml]
@(
Html.Syncfusion().MultiColumnDropDown<Student>("Multicolumndropdown")
.Datasource((IEnumerable) ViewData["data"])
.DisplayExpression(new int[] {2, 3, 5})
.Width(500)
.AllowFiltering(true)
.Text("--Select--")
))
Controller
/// <summary>
/// Used for rendering the MultiColumnDropDown initially.
/// </summary>
/// <returns>View page; it displays
the MultiColumnDropDown.</returns>
public ActionResult Index()
{
var Data = new
StudentDataContext().AutoFormatStudent.Take(200);
ViewData["data"] = Data;
return View(Data);
}
2. In order to work with filtering actions, create a Post method for Index actions and bind the
data source to MultiColumnDropDown as in the following code:
261.
Controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index (PagingParams args)
{
IEnumerable data =new
StudentDataContext().AutoFormatStudent.Take(20);
return data.GridActions<Student>();
}
262.
3. Run the application. The MultiColumnDropDown control will appear as shown below:
263.
View[ASPX]
<%=Html.Syncfusion().MultiColumnDropDown<Student>("Multidropdown",(Mult
View[cshtml]
@( Html.Syncfusion().MultiColumnDropDown<Student>("Multidropdown",
(MultiColumnDropDownModel) ViewData["dropdown"])))
264.
265. Create an instance for MultiColumnDropDownModel and assign Datasource to the
model.
266.
Controller
// Create instance to MultiColumnDropDownModel and assign properties.
MultiColumnDropDownModel dropdown = new
MultiColumnDropDownModel()
{
Datasource = new
StudentDataContext().JSONStudent.Skip(0).Take(30).ToList(),
Text = "--Select--",
DisplayExpression = new int[3] { 2, 3, 5 },
Width = 500
};
267.
268. Enable/disable the filtering feature using the AllowFiltering property.
269.
Controller
// Create instance to MultiColumnDropDownModel and assign properties.
MultiColumnDropDownModel dropdown = new
MultiColumnDropDownModel()
{
Datasource = new
StudentDataContext().JSONStudent.Skip(0).Take(30).ToList(),
Text = "--Select--",
DisplayExpression = new int[3] { 2, 3, 5 },
Width = 500,
AllowFiltering = true
};
270.
271. Pass the model to View using ViewData().
Controller
272. In order to work with filtering actions, create a Post method for Index actions and bind
the data source to MultiColumnDropDown as shown in the following code.
273.
Controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index (PagingParams args)
{
IEnumerable data =new
StudentDataContext().AutoFormatStudent.Take(20);
return data.GridActions<Student>();
}
274.
275. Run the application. The MultiColumnDropDown control will appear as shown below:
<%=Html.Syncfusion().MultiColumnDropDown<Sample.Models.Student>("MultiC
olumnDD").ActionMode(ActionMode.JSON)
.DataSource(Model)
.Columns(column=>{column.Add(p => p.Title).HeaderText("Course
Title");
column.Add(P => P.Duration).Format("{Duration} hrs");
column.Add(p =>
p.CourseFees).Format("{CourseFees:c}").HeaderText("Course Fees");
column.Add(p => p.CGPA);
}).AllowSorting(true).DisplayExpression(new int[3]{1,3,4})
.PopupPanelWidth(700).Width(700).AllowFiltering(true)
%>
View[Razor]
@{Html.Syncfusion().MultiColumnDropDown<Sample.Models.Student>("MultiCo
lumnDD").ActionMode(ActionMode.JSON)
.DataSource(Model)
.Columns(column=>{column.Add(p => p.Title).HeaderText("Course
Title");
.PopupPanelWidth(700).Width(700).AllowFiltering(true).Render();
Controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult index(PagingParams args)
{
IEnumerable data = new
StudentDataContext().Student.Take(200).ToList();
ActionResult result = data.GridJSONActions<Student>();
return result;
The following steps help you to include code samples in your view:
1. Create a model in the application (Refer to: How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to: How to>Strongly Typed View).
3. Open the view and place the cursor where you would like to insert the code sample.
4. Press CTRL+K, X (or) right-click on view and select the Insert Snippet option.
5. Select Syncfusion ASP.NET MVC 2 (or) Syncfusion ASP.NET MVC 3 (or) Syncfusion
ASP.NET MVC 4 using the arrow keys and press enter to see a list of samples available.
The following table illustrates the code sample available for the Grid control for Syncfusion
ASP.NET MVC 3.
5 How to
Adding a Model to the Application
After an MVC application is created, a model has to be added. The model is a place from which
the data can be retrieved by the controller. This section guides you through the step-by-step
procedure for adding a model.
Figure 334: Context Menu Displayed when Clicking the Models Folder
Note: The Add New Item {Application Name} is displayed. The Categories window displays the
components available under the Visual C# program. The templates window displays the templates
under the selected elements.
Note: The Visual Studio installed templates are displayed in the Templates window.
Note: This step is optional and should be performed only when you want to attach a database
with the model. For details, see http://weblogs.asp.net/scottgu/archive/2007/05/29/linq-to-sql-
part-2-defining-our-data-model-classes.aspx.
Note: The data classes are added under the Model folder.
7. In the Name box, enter Northwind.dbml and click the Add button.
278. Now Northwind LINQ to SQL classes are created in your application and the Object
Relational Designer appears.
8. Drag and drop the tables from the Server Explorer window onto the Object Relational
Designer to create LINQ to SQL classes that represent particular database tables. You
need to add all Northwind database tables onto the Object Relational Designer.
• Syncfusion.Core.dll
• Syncfusion.Linq.Base.dll
• Syncfusion.Shared.Mvc.dll
• Syncfusion.Theme.Base.dll
• Syncfusion.Grid.Mvc.dll
• Syncfusion.XlsIO.Mvc.dll
2. Add the following namespaces in the <namespaces> tag. Refer the following code example,
<namespaces>
<add namespace="Syncfusion.Grid.Mvc"/>
<add namespace="Syncfusion.Shared.Mvc"/>
</namespaces>
Note: The namespaces should also be added in the web.config file within the View folder.
3. Refer the following script files in Layout.cshtml as shown in the following code example.
<script src="@Url.Content("~/Scripts/jquery-1.7.1.min.js")"
type="text/javascript"></script>
4. The ScriptManager() method should be placed after all the components on the page. Add this
line at the end of the Layout.cshtml.
@{Html.Syncfusion().ScriptManager().Render();}
5. Suggest you to add the following handlers under the handlers tag in <system.webServer> and
httpHandlers tag in <system.web>. Refer the following code example.
<system.web>
<httpHandlers>
<add verb="GET,HEAD" path="MvcResourceHandler.axd"
type="Syncfusion.Mvc.Shared.MvcResourceHandler, Syncfusion.Shared.Mvc,
Version=10.344.0.43, Culture=neutral, PublicKeyToken=3d67ed1f87d44c89"
validate="false"/>
</httpHandlers>
</system.web>
<system.webServer>
<handlers>
6. AjaxMin dll is added as reference for the purpose of Minification of Stylesheets and Scripts,
and can be copied into the precompiled assemblies folder installed with the product. Refer the
following code example:
[ASPX]
Note: The View data class drop-down list will be empty until you successfully build your
application. It is a good idea to select the menu option Build to build a solution before opening the
Add New dialog.
6. In the View data class drop-down, make the model an IEnumerable collection.
View
<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage<IEnumerable<MvcSampleApplication.Mode
ls.Order>>" %>
3. Select the ADO.NET Entity Data Model template, give the Entity Data Model the name
PubsDBModel.edmx, and click the Add button. Clicking the Add button launches the Data
Model Wizard.
4. In the Choose Model Contents step, choose the Generate from database option and
click the Next button (see Figure 343).
2. In the Choose Your Data Connection step, select the Pubs.mdf database connection,
enter the entities connection settings name PubsEntities, and click the Next button (see
Figure 344).
3. In the Choose Your Database Objects step, select all the database tables and click the
Finish button (see Figure 345).
When you are finished, you will be able to find the following image.
1. Right-click the Models folder in the Solution Explorer window and select the menu option
Add New Item.
2. In the Add New Item window, select the Web category (see Figure 347).
3. Select the Class file and give the class file name Student.cs and click the Add button.
4. Create a student class containing University Code, Course Fees, CGPA, Course ID,
Duration, and Course Title as properties.
279.
/// <summary>
/// Student class.
/// </summary>
public class Student
{
#region Properties
/// <summary>
/// Gets or sets the student name.
/// </summary>
public long UniversityCode { get; set; }
/// <summary>
/// Gets or sets the course title.
/// </summary>
public string Title { get; set; }
/// <summary>
/// Gets or sets the duration in days of the course.
/// </summary>
public int Duration { get; set; }
/// <summary>
/// Gets or sets course fees.
/// </summary>
public double CourseFees { get; set; }
/// <summary>
/// Gets or sets CGPA.
/// </summary>
public double CGPA { get; set; }
#endregion
}
5. Create another DataContext class to generate the students list as shown below.
280.
/// <summary>
/// StudentDataContext class.
/// </summary>
public class StudentDataContext
{
#region Properties
/// <summary>
/// Gets the courses in an IQueryable format.
/// </summary>
public List<Student> Student
{
get
{
List<Student> student = new List<Student>();
Student stu = new Student();
int code = 10000;
for (long i = 0; i < 100; i++)
{
Student[] s = new Student[10];
s[0] = new Student() { UniversityCode = code
+ 1, CourseFees = 2000.00, CGPA = 7.52, Duration = 90, Title =
"Distributed Component Architecture" };
s[1] = new Student() { UniversityCode = code
+ 2, CourseFees = 1000.00, CGPA = 9.55, Duration = 60, Title =
"Data Structures" };
s[2] = new Student() { UniversityCode = code
+ 3, CourseFees = 1750.00, CGPA = 9.03, Duration = 75, Title =
"Neural Networks" };
s[3] = new Student() { UniversityCode = code
+ 4, CourseFees = 2000.00, CGPA = 8.91, Duration = 90, Title =
"Genetic Algorithms" };
code += 10;
}
return student;
}
}
}
1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. In the Index view, you can use DataSource to bind the data source. Then you need to
explicitly specify the type of the data item.
View[Aspx]
<%=Html.Syncfusion().Grid<MvcSampleApplication.Models.Order>("Fla
tGrid")
.Datasource((IEnumerable<MvcSampleApplication.Models.Order>)ViewD
ata["data"])
.EnablePaging()
.EnableSorting()
.ActionMode("Server")
/// <summary>
/// Used to bind the grid.
/// </summary>
/// <returns>View page; it displays the grid.</returns>
public ActionResult Index()
{
var data = new NorthwindDataContext().Orders.Take(200);
return View(data);
}
4. In order to work with paging and sorting actions, create a Post method for Index actions
and bind the data source to the grid as shown in the following code sample.
Controller
/// <summary>
/// Paging/sorting requests are mapped to this method. This
method invokes the HtmlActionResult
/// from the grid. The required response is generated.
/// </summary>
/// <param name="args">Contains paging properties.</param>
/// <returns>
/// HtmlActionResult returns the data displayed in the grid.
/// </returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new
NorthwindDataContext().Orders.Take(200);
return data.GridActions<Order>();
2. In the drop-down list at the top, make sure that .NET Framework 4.0 is selected.
3. In the Installed Templates panel, expand either Visual Basic or Visual C#, and then click
Web.
4. Select ASP.NET MVC 3 Web Application in the main window.
5. In the Name box, type MvcSampleApplication.
6. In the Location box, type a name for the project folder.
7. If you want the name of the solution to differ from the project name, type a name in the
Solution name box.
8. Select the Create directory for solution check box.
9. Click OK. The New ASP.NET MVC 3 Project dialog box is displayed.
10. Select “Internet Application” from the New ASP.NET MVC 3 Project dialog box.
11. Click OK.
282.
Note: If you want to create a unit test for your project, check the “Create a unit test project” in
the New ASP.NET MVC 3 Project dialog box and click OK.
The new MVC application project and a test project are generated. (If you are using the Standard
or Express editions of Visual Studio, the test project is not created.)
The folder structure of an MVC project differs from that of an ASP.NET Web site project. The
MVC project contains the following folders:
Content, which is for content support files. This folder contains the cascading style sheet
(.css file) for the application.
Controllers, which is for controller files. This folder contains the application's sample
controllers, which are named AccountController and HomeController. The
AccountController class contains login logic for the application. The HomeController
class contains logic that is called by default when the application starts.
Models, which is for data-model files such as LINQ-to-SQL .dbml files or data-entity files.
Scripts, which is for script files such as those that support ASP.NET AJAX and jQuery.
Views, which is for view page files. This folder contains three subfolders: Account,
Home, and Shared. The Account folder contains views that are used as UI for logging in
and changing passwords. The Home folder contains an Index view (the default starting
page for the application) and an About page view. The Shared folder contains the
master-page view for the application.
The newly generated MVC project is a complete application that you can compile and run without
change. The following illustration shows what the application looks like when it runs in a browser.
Adding the Grid control to the application includes the following steps:
Figure 352: Add Reference Option Displayed on Right-Clicking the References Folder
Note: The Add Reference dialog box appears and the .NET tab is highlighted by default. The
assemblies for the MVC application are listed here.
The following table illustrates the MVC versions and their corresponding assembly versions.
2. On the Solution Explorer click the Scripts folder. The lists of available scripts are
displayed.
[Site.Master]
<head runat="server">
…………
…………
</head>
1. In the Solution Explorer, double-click the Web.config file. (There will be two Web.config
files. Refer to the one in the root folder.)
2. Add the following assemblies in the Web.config page under the <compilation> tag:
Syncfusion.Core, Syncfusion.Grid.Mvc, Syncfusion.Linq.Base and
Syncfusion.Shared.Mvc.
[Web.config]
<system.web>
<compilation debug="true" targetFramework="4.0">
<assemblies>
…………
…………
3. Note: X in the above code corresponds to the correct version number of the Essential
Studio version that you are currently using.Add the Syncfusion.Mvc.Shared and
Syncfusion.Mvc.Grid namespaces under the <namespaces> tag.
283.
[web.config]
<system.web>
<pages>
<namespaces>
……….
……….
<add namespace="Syncfusion.Mvc.Shared"/>
<add namespace="Syncfusion.Mvc.Grid"/>
</namespaces>
</pages>
</system.web>
4. Register the handlers under the <httpHandlers> and <handlers> tags in the
Web.config file by using the code below.
284.
[web.config]
<system.web>
………..
………..
<httpHandlers>
<add verb="GET,HEAD" path="MvcResourceHandler.axd"
type="Syncfusion.Mvc.Shared.MvcResourceHandler, Syncfusion.Shared.Mvc,
Version=x.x340.x.x, Culture=neutral, PublicKeyToken=3d67ed1f87d44c89"
validate="false"/>
</httpHandlers>
</system.web>
……..
<system.webServer>
…….
…….
<handlers>
<remove name="MvcResourceHandler"/>
<add verb="GET,HEAD" name="MvcResourceHandler"
path="MvcResourceHandler.axd"
type="Syncfusion.Mvc.Shared.MvcResourceHandler,
Syncfusion.Shared.Mvc, Version=x.x340.x.x, Culture=neutral,
PublicKeyToken=3d67ed1f87d44c89"/>
</handlers>
</system.webServer>
Note:
VS2010 automatically registers all ASP.NET handlers inside the machine.config file. So add
the <httpHandlers> and <handlers> tags under <system.web> and <system.webServer>
respectively in the web.config file. For more information, refer to Clean Web.Config Files (VS
2010 and .NET 4.0 Series)
X. in the above code corresponds to the correct version number of the Essential Studio
version that you are currently using.
StyleManager is a new CSS resource manager that helps in registering CSS files which enables
the minification, compression, and combination of CSS resources for ASP.NET MVC Web
applications. The files in StyleManager resources are set to be combined, minified, and
compressed (either gzip or deflate, depending on your browser) before being sent to the browser.
All are done using a single HTTP request per resource set.
Add the StyleManager extension method in the HEAD element of the view pages (in most cases,
it is reasonable to call it within the Site.Master page). Use the Register method to register the
Grid component.
View[ASPX]
<%=Html.Syncfusion().StyleManager()
.Register(styleSheet =>
{
styleSheet.Add(ComponentType.Grid);
}) %>
The ScriptManager() method should be placed after all the components on the page. Generally,
you can use this method at the end of the master page.
View[ASPX]
<body>
…
…
<%=Html.Syncfusion().ScriptManager()%>
</body>
Note: Add this ScriptManager() at the end of a <body> tag. Don’t add this in the top of a <body>
tag.
285.
View[ASPX]
<%=Html.Syncfusion().Grid<MvcSampleApplication.Models.Order>("FlatGrid"
)
.Datasource(Model)
.EnablePaging()
.EnableSorting()
.Column( column => {
column.Add(c => c.OrderID).HeaderText("Order ID");
column.Add(c => c.CustomerID).HeaderText("Customer ID");
column.Add(c => c.EmployeeID).HeaderText("Employee ID");
column.Add(c => c.OrderDate).HeaderText("Order
Date").Format("{OrderDate:dd/mm/yyyy}");
column.Add(c => c.Freight).HeaderText("Freight");
})
%>
Note: This is of the type: GridBuilder<T> Grid<T>(this HtmlHelper html, string id) where T: class
It is important that the ID used in the FlatGrid.aspx file and in the HomeController.cs file should
match in order to ensure binding of the properties to the control.
4. Add two methods in HomeController (one for loading the view and one for handling the
grid paging and sorting actions).
[Controller]
/// <summary>
/// Used to bind the Grid.
/// </summary>
/// <returns>View page, displays the Grid</returns>
public ActionResult Index()
{
var data=new NorthwindDataContext().Orders.Take(200);
return View(data);
}
/// <summary>
/// Paging/sorting Requests are mapped to this method. This method
invokes the
/// HtmlActionResult from the grid. The required response is
generated.
/// </summary>
/// <param name="args">Contains paging properties </param>
/// <returns>
/// HtmlActionResult returns the data displayed on the grid.
/// </returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new NorthwindDataContext().Orders.Take(200);
return data.GridActions<Order>();
}
1. Create a model into application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. Add the following code in the Index.aspx file, to create the Grid control in the view:
View[ASPX]
<%=Html.Syncfusion().Grid<MvcSampleApplication.Models.Order>("Fla
tGrid","GridModel",
column => {
column.Add(c => c.OrderID).HeaderText("Order ID");
column.Add(c => c.CustomerID).HeaderText("Customer
ID");
column.Add(c => c.EmployeeID).HeaderText("Employee
ID");
column.Add(c => c.OrderDate).HeaderText("Order
Date").Format("{OrderDate:dd/mm/yyyy}");
column.Add(c => c.Freight).HeaderText("Freight");
})
%>
[Controller]
/// <summary>
/// Used to bind the Grid.
/// </summary>
/// <returns>View page, it displays the Grid</returns>
public ActionResult Index()
{
GridPropertiesModel<Order> model = new
GridPropertiesModel<Order>()
{
DataSource = new
NorthwindDataContext().Orders.Take(200),
AllowPaging = true,
AllowSorting = true
};
ViewData["GridModel"] = model;
return View();
}
Code details:
a. Objects created for GridPropertiesModel and the following grid properties are assigned
to model
DataSource—Gets or sets a data source for the Grid control
AllowPaging—Gets or sets a value indicating whether the paging feature is enabled.
AllowSorting—Gets or sets a value indicating whether the sorting feature is enabled.
b. Pass the model to view using ViewData. This will pass the grid properties from the
controller to the view.
Syntax: ViewData["model_id"] = object_name;
6. In order to work with paging/sorting actions, create a post method for Index actions and
update the following code in this method.
[Controller]
/// <summary>
/// Paging/sorting Requests are mapped to this method. This
method invokes the HtmlActionResult
/// from the grid. The required response is generated.
/// </summary>
/// <param name="args">Contains paging properties </param>
/// <returns>
/// HtmlActionResult returns the data displayed on the grid.
/// </returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new
NorthwindDataContext().Orders.Take(200);
return data.GridActions<Order>();
}
Note: Essential Grid is fully AJAX enabled. For paging/sorting/filtering/editing actions the entire
page will not be refreshed. The grid contents alone refresh using AJAX calls. The methods above are
necessary to achieve the grid actions.
Code details:
a. Get the data source and store it in an IEnumerable collection.
b. Call the GridAction helper with the Type of Model, which invokes the custom action
result. This will process the data source and return the required response while calling
paging and sorting actions.
7. Run the application.
A sample which demonstrates a basic Grid control can be downloaded from the following link.
http://help.syncfusion.com/Support/grid_mvc/v8.3.0.20/UG/MvcGridSample.zip
Note: The version number for the assemblies has been set to 10.2.0.75 in the Web.config file of
the attached sample. Change the version number to the appropriate version in the Web.config files
(available in root directory).
Figure 362: Add Reference Option Displayed on Right-Clicking the References Folder
Note: The Add Reference dialog box appears and the .NET tab is highlighted by default. The
assemblies for the MVC application are listed here.
The following table illustrates the MVC versions and their corresponding assembly versions.
1. On the Solution Explorer click the Scripts folder. The lists of available scripts is displayed.
286. Import the following JavaScript files onto the _Layout.cshtml page.
jquery-1.7.min.js
MicrosoftAjax.js
[_Layout.cshtml]
<head runat="server">
…………
…………
<script src="@Url.Content("~/Scripts/jquery-1.7.min.js")"
type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/MicrosoftAjax.js")"
type="text/javascript"></script>
</head>
[_Layout.vbhtml]
<head runat="server">
<script src="@Url.Content("~/Scripts/jquery-1.7.min.js")"
type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/MicrosoftAjax.js")"
type="text/javascript"></script>
</head>
On the Solution Explorer, double-click the Web.config file. (There will be two Web.config files.
Refer to the one in the root folder.)
Add the following assemblies in the Web.config page under the <compliation> tag:
Syncfusion.Core, Syncfusion.Grid.Mvc, Syncfusion.Linq.Base, and
Syncfusion.Shared.Mvc.
[Web.config]
<system.web>
<compilation debug="true" targetFramework="4.0">
<assemblies>
………….
………….
<add assembly="Syncfusion.Core, Version=x.x040.x.x,
Culture=neutral, PublicKeyToken=632609b4d040f6b4"/>
<add assembly="Syncfusion.Linq.Base, Version=x.x040.x.x,
Culture=neutral, PublicKeyToken=3d67ed1f87d44c89"/>
<add assembly="Syncfusion.Shared.Mvc, Version=x.x340.x.x,
Culture=neutral, PublicKeyToken=3d67ed1f87d44c89"/>
<add assembly="Syncfusion.Grid.Mvc, Version=x.x340.x.x,
Culture=neutral, PublicKeyToken=3d67ed1f87d44c89"/>
</assemblies>
</compilation>
</system.web>
Note: X. in the above code corresponds to the correct version number of the Essential Studio
version that you are currently using.
1. Register the handlers under the <httpHandlers> and <handlers> tags in the
Web.config file by using the code below.
[Web.config]
<system.web>
………..
………..
<httpHandlers>
<add verb="GET,HEAD" path="MvcResourceHandler.axd"
type="Syncfusion.Mvc.Shared.MvcResourceHandler, Syncfusion.Shared.Mvc,
Version=x.x340.x.x, Culture=neutral, PublicKeyToken=3d67ed1f87d44c89"
validate="false"/>
</httpHandlers>
</system.web>
……..
<system.webServer>
…….
…….
<handlers>
<remove name="MvcResourceHandler"/>
<add verb="GET,HEAD" name="MvcResourceHandler"
path="MvcResourceHandler.axd"
type="Syncfusion.Mvc.Shared.MvcResourceHandler,
Syncfusion.Shared.Mvc, Version=x.x340.x.x, Culture=neutral,
PublicKeyToken=3d67ed1f87d44c89"/>
</handlers>
</system.webServer>
Note: In VS2010, <httpHandlers> and <handlers> are registered inside the Machine.config file.
For more information: http://weblogs.asp.net/scottgu/archive/2009/08/25/clean-web-config-
files-vs-2010-and-net-4-0-series.aspx
Please add the <httpHandlers> and <handlers>tags under <system.web> and
<system.webServer> respectively.
Note: X in the above code corresponds to the correct version number of the Essential Studio
version that you are currently using.
[Web.config]
<system.web.webPages.razor>
<pages pageBaseType="System.Web.Mvc.WebViewPage">
<namespaces>
…………..
…………..
<add namespace="Syncfusion.Mvc.Shared"/>
<add namespace="Syncfusion.Mvc.Grid"/>
</namespaces>
</pages>
</system.web.webPages.razor>
StyleManager is a new CSS resource manager that helps in registering CSS files which enables
the minification, compression, and combination of CSS resources for ASP.NET MVC Web
applications. The files in StyleManager resources are set to be combined, minified, and
compressed (either gzip or deflate, depending on your browser) before being sent to the browser.
All are done using a single HTTP request per resource set.
Add the StyleManager extension method in the HEAD element of the view pages (in most cases,
it is reasonable to call it within the _Layout.cshtml page). Use the Register method to register
the Grid component.
View[cshtml]
@{Html.Syncfusion().StyleManager()
.Register(stylesheets =>
{
stylesheets.Add(ComponentType.Grid);
}).Render();}
The ScriptManager() method should be placed after all the components on the page. Generally,
you can use this method at the end of the master page.
View[cshtml]
<body>
…
…
@{Html.Syncfusion().ScriptManager().Render();}
</body>
Note: Add this ScriptManager() at the end of the <body> tag. Don’t add this in top of the <body>
tag.
3. Add the following code in the Index.cshtml file to create the Grid control in the view:
View[cshtml]
@{ Html.Syncfusion().Grid<Sample.Models.Order>("FlatGrid")
.Datasource(Model)
.EnablePaging()
.EnableSorting()
.Column( column => {
column.Add(c => c.OrderID).HeaderText("Order ID");
column.Add(c => c.CustomerID).HeaderText("Customer ID");
column.Add(c => c.EmployeeID).HeaderText("Employee ID");
column.Add(c => c.OrderDate).HeaderText("Order
Date").Format("{OrderDate:dd/mm/yyyy}");
column.Add(c => c.Freight).HeaderText("Freight");
})
.Render();
}
Note: This is of the type: GridBuilder<T> Grid<T>(this HtmlHelper html, string id) where T: class
It is important that the ID used in the FlatGrid.cshtml file and in the HomeController.cs file
should match in order to ensure binding of the properties to the control.
4. Add two methods in HomeController (one for loading the view and one for handling the
grid paging/sorting actions).
[Controller]
/// <summary>
/// Used to bind the Grid.
/// </summary>
/// <returns>View page, displays the Grid</returns>
public ActionResult Index()
{
var data=new NorthwindDataContext().Orders.Take(200);
return View(data);
}
/// <summary>
/// Paging/sorting requests are mapped to this method. This method
invokes the
/// HtmlActionResult from the grid. The required response is
generated.
/// </summary>
/// <param name="args">Contains paging properties </param>
/// <returns>
/// HtmlActionResult returns the data displayed on the grid.
/// </returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new NorthwindDataContext().Orders.Take(200);
return data.GridActions<Order>();
}
View[cshtml]
@(
Html.Syncfusion().Grid<MvcSampleApplication.Models.Order>("FlatGrid","G
ridModel",
column =>{
column.Add(c => c.OrderID).HeaderText("Order ID");
column.Add(c => c.CustomerID).HeaderText("Customer
ID");
column.Add(c => c.EmployeeID).HeaderText("Employee
ID");
column.Add(c => c.OrderDate).HeaderText("Order
Date").Format("{OrderDate:dd/mm/yyyy}");
column.Add(c => c.Freight).HeaderText("Freight");
}))
/// <summary>
/// Used to bind the Grid.
/// </summary>
/// <returns>View page, it displays the Grid</returns>
public ActionResult Index()
{
GridPropertiesModel<Order> model = new
GridPropertiesModel<Order>()
{
DataSource = new
NorthwindDataContext().Orders.Take(200),
AllowPaging = true,
AllowSorting = true
};
ViewData["GridModel"] = model;
return View();
}
Code details:
a. Object created for GridPropertiesModel and the following grid properties are assigned to
model
DataSource—Gets or sets a data source for the Grid control.
AllowPaging—Gets or sets a value indicating whether the paging feature is enabled.
AllowSorting—Gets or sets a value indicating whether the sorting feature is enabled.
b. Pass the model to the view using ViewData. This will pass the grid properties from the
controller to the view.
Syntax:
ViewData["model_id"] = object_name;
6. In order to work with paging and sorting actions, create a post method for Index actions and
update the following code in this method.
[Controller]
/// <summary>
/// Paging/sorting requests are mapped to this method. This
method invokes the HtmlActionResult
/// from the grid. The required response is generated.
/// </summary>
/// <param name="args">Contains paging properties </param>
/// <returns>
/// HtmlActionResult returns the data displayed on the grid.
/// </returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new
NorthwindDataContext().Orders.Take(200);
return data.GridActions<Order>();
}
Note: Essential Grid is fully AJAX enabled. For paging/sorting/filtering/editing actions the entire
page will not be refreshed. The grid contents alone refresh using AJAX calls. The methods above are
necessary to achieve the grid actions.
Code details:
a. Get the data source and store it in a IEnumerable collection.
b. Call the GridAction helper with the Type of Model which invokes the custom action
result. This will process the data source and return the required response while calling
paging and sorting actions.
A sample which demonstrates a basic Grid control can be downloaded from the following link:
http://www.syncfusion.com/uploads/redirect.aspx?&team=support&file=MvcGridSample(Razor)13
79183234.zip
Note: The version number for the assemblies has been set to 10.2.0.75 in the Web.config file of
the attached sample. Change the version number to the appropriate version in the Web.config files
(available in root directory).
The Add Reference dialog box appears and the .NET tab is highlighted by default. The
assemblies for the MVC application are listed here.
b. In the Solution Explorer click the Scripts folder. The lists of scripts available are
displayed.
[_Layout.vbhtml]
<head runat="server">
<script src="@Url.Content("~/Scripts/jquery-1.7.min.js")"
type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/MicrosoftAjax.js")"
type="text/javascript"></script>
</head>
b. Add the following assemblies in the Web.config page under the <compilation> tag:
Syncfusion.Core
Syncfusion.Grid.Mvc
Syncfusion.Linq.Base
Syncfusion.Theme.Base
Syncfusion.Shared.Mvc
[Web.config]
<system.web>
<compilation debug="true" targetFramework="4.0">
<assemblies>
<add assembly="Syncfusion.Core, Version=x.x040.x.xx,
Culture=neutral, PublicKeyToken=632609b4d040f6b4"/>
<add assembly="Syncfusion.Linq.Base, Version= x.x040.x.xx,
Culture=neutral, PublicKeyToken=3d67ed1f87d44c89"/>
<add assembly="Syncfusion.Shared.Mvc, Version= x.x340.x.xx,
Culture=neutral, PublicKeyToken=3d67ed1f87d44c89"/>
<add assembly="Syncfusion.Grid.Mvc, Version= x.x340.x.xx,
Culture=neutral, PublicKeyToken=3d67ed1f87d44c89"/>
<add assembly="Syncfusion.Theme.Base, Version= x.x340.x.xx,
Culture=neutral, PublicKeyToken=3d67ed1f87d44c89" />
</assemblies>
</compilation>
Register the handlers under the <httpHandlers> and <handlers> tags in the Web.config file
by using the code below.
[Web.config]
<system.web>
<httpHandlers>
<add verb="GET, HEAD" path="MvcResourceHandler.axd"
type="Syncfusion.Mvc.Shared.MvcResourceHandler, Syncfusion.Shared.Mvc,
Version= x.x340.x.xx, Culture=neutral, PublicKeyToken=3d67ed1f87d44c89"
validate="false"/>
</httpHandlers>
</system.web>
<system.webServer>
<handlers>
<remove name="MvcResourceHandler"/>
<add verb="GET, HEAD" name="MvcResourceHandler"
path="MvcResourceHandler.axd"
type="Syncfusion.Mvc.Shared.MvcResourceHandler, Syncfusion.Shared.Mvc,
Version= x.x340.x.xx, Culture=neutral,
PublicKeyToken=3d67ed1f87d44c89"/>
</handlers>
</system.webServer>
Note: X. in the above code corresponds to the correct version number of the Essential Studio
version that you are currently using.
[Web.config]
<system.web.webPages.razor>
<pages pageBaseType="System.Web.Mvc.WebViewPage">
<namespaces>
<add namespace="Syncfusion.Mvc.Shared"/>
<add namespace="Syncfusion.Mvc.Grid"/>
</namespaces>
</pages>
</system.web.webPages.razor>
[vbhtml]
View[Razor]
@Code
Dim styleManager =
Html.Syncfusion.StyleManager.Register(Function(register)
register.Add("~/Content/Site.css")) 'Register CSS files.
styleManager.Register(Function(register)
register.Add(ComponentType.Grid)) 'Register controls.
'Render the style manager.
styleManager.Render()
End Code
StyleManager is a new CSS resource manager that helps in registering CSS files which enables
the minification, compression, and combination of CSS resources for ASP.NET MVC Web
applications. The files in StyleManager resources are set to be combined, minified, and
compressed (either gzip or deflate, depending on your browser) before being sent to the browser.
All are done using a single HTTP request per resource set.
Add the StyleManager extension method in the HEAD element of the view pages (in most cases,
it is reasonable to call it within the _Layout.vbhtml page). Use the Register method to register
the Grid component.
Razor[vbhtml]
@code
Dim styleManager = Html.Syncfusion.StyleManager
styleManager.Register(Function(register)
register.Add("~/Content/Site.css"))
styleManager.Register(Function(register)
register.Add(ComponentType.Grid))
The ScriptManager() method should be placed after all the components on the page. Generally,
you can use this method at the end of the master page.
Razor[vbhtml]
<body>
…
…
@code
Html.Syncfusion().ScriptManager().Combine(true).Minify(true).Render()
End Code
</body>
Note: Add this ScriptManager() at the end of the <body> tag. Don’t add this in top of the <body>
tag.
[Razor]
@Code
Dim gridbuilder = Html.Syncfusion().Grid(Of
GridSample.Order)("SampleGrid").Datasource(Model)
GridSample.Order)
c.OrderDate).HeaderText("OrderDate").Format("{OrderDate:dd/MM/yyyy}"))
gridbuilder.EnablePaging()
gridbuilder.EnableGrouping()
gridbuilder.EnableSorting()
gridbuilder.Render()
End Code
5. Add two methods in HomeController (one for loading the view and one for handling the
grid paging and sorting actions)
[vbhtml]
Controller
<AcceptVerbs(HttpVerbs.Post)> _
Public Function Index(ByVal args As PagingParams) As
ActionResult
This section will walk you through all the features of the Grid control.
5.7.6.1 Appearance
Essential Grid has several built-in skins that make styling extremely easy. It is also possible to
easily format the data displayed in the grid.
Essential Grid for ASP.NET MVC contains 14 built-in skins to easily customize appearance.
Essential Grid's AutoFormat property allows you to apply predefined skins to the control. Some
of the available skins are illustrated in detail in the Built-in Skin Styles section.
5.7.6.2 Grouping
Essential Grid has built-in capability to group data by one or more columns. Grouping is done on
the server and the required data is only sent back to the client by using AJAX, so the operation is
greatly optimized for speed and data transfer. The records displayed in the grid can be grouped
by one or more columns.
Grouping operations can be done programmatically or can be initiated by you. You can simply
drag and drop the desired column header to a group drop area located at the top of the grid to
group by a particular column. Refer to the Grouping topic to know more.
5.7.6.3 Sorting
Essential Grid has built-in support for sorting by one or more columns. It is also possible to sort
by using custom logic.
a. Sorting columns
The default grid settings allow the grid data to be sorted in ascending or descending
order by the selected column.
b. Multicolumn sorting
The default grid settings allow multiple columns to be sorted by clicking the desired
column headers while holding CTRL. There are also options for clearing the sort and
disabling sorting on a specific column. For more information about this feature, see
Sorting.
5.7.6.4 Filtering
Essential Grid allows you to filter data in the control using the Filter menu. See Filtering.
5.7.6.5 Paging
Essential Grid includes a pager bar that can be used to easily navigate to the required page when
the grid has data that spans several pages. See Paging.
a. Pager bar
Essential Grid for ASP.NET MVC includes a pager bar that can be used to navigate to a
specific page. There are also options to control the number of pages displayed.
5.7.6.6 Editing
Essential Grid provides built-in support inserting, updating, and deleting records inside the grid.
The grid provides three types of editing modes. See Editing.
5.7.6.7 Exporting
The Grid control has built-in support for exporting a grid to Excel. You can download data from
the Grid control to an Excel worksheet for offline verification and/or computation. This can be
achieved by using the GridExcelExportActionResult<T> extension. See Exporting.
5.7.6.8 Summaries
You can easily create summaries for grid records using summary row descriptor collections. Pre-
built summary types include sum, average, and summary. See Summaries.
5.7.6.9 Scrolling
Specify a width and height for the control and the grid will automatically show scroll bars if
necessary. See Scrolling.
Essential Grid uses the Format() and CssClass() methods to format columns.
Conditional formatting
Essential Grid has built-in support for conditional formatting. This feature allows you to format the
grid cells based on a certain condition. This can be achieved by defining a
GridConditionalFormatDescriptor<T> for the grid.
Essential Grid supports the addition of unbound columns in the grid. Please refer to the Unbound
Column section.
Essential Grid provides support for dragging and dropping records between grids and HTML
elements. See Drag and Drop.
Essential Grid has several client-side interactions to enhance the end-user experience. See
Client-Side Events and Methods.
a. Selection
Essential Grid has client-side interaction options to select a single row, a group or rows or the
whole grid. For details, see Selection.
b. Column resizing
Essential Grid's column widths can be interactively adjusted by dragging and resizing the
desired columns.
c. Drag-and-drop support:
Essential Grid's column positions can be re-arranged by dragging a desired column
header to a new location. Cue arrows provide hints about the destination location.
The Add Reference dialog box appears and the .NET tab is highlighted by default. The
assemblies for the MVC application are listed in the dialog box.
Syncfusion.Core
Syncfusion.Linq.Base
Syncfusion.Theme.Base
Syncfusion.Grid.Mvc
Syncfusion.Shared.Mvc
3. Click OK.
2. In the Solution Explorer, click the Scripts folder. The list of scripts available is
displayed.
<head runat="server">
<script src="@Url.Content("~/Scripts/jquery-1.7.min.js")"
type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/MicrosoftAjax.js")"
type="text/javascript"></script>
</head>
1. In the Solution Explorer, double-click the Web.config file in the root folder.
2. Add the following assemblies in the Web.config page under the <compilation> tag:
Syncfusion.Core
Syncfusion.Grid.Mvc
Syncfusion.Shared.Mvc
Syncfusion.Linq.Base
Syncfusion.Theme.Base
[Web.config]
<system.web>
<compilation debug="true" targetFramework="4.0">
<assemblies>
<add assembly="Syncfusion.Core, Version=X.X045.X.X,
Culture=neutral, PublicKeyToken=632609b4d040f6b4"/>
<add assembly="Syncfusion.Linq.Base, Version=X.X045.X.X,
Culture=neutral, PublicKeyToken=3d67ed1f87d44c89"/>
<add assembly="Syncfusion.Theme.Base, Version=X.X045.X.X,
Culture=neutral, PublicKeyToken=3d67ed1f87d44c89"/>
<add assembly="Syncfusion.Grid.Mvc, Version=X.X445.X.X,
Culture=neutral, PublicKeyToken=3d67ed1f87d44c89"/>
<add assembly="Syncfusion.Shared.Mvc, Version=X.X445.X.X,
Culture=neutral, PublicKeyToken=3d67ed1f87d44c89"/>
</assemblies>
</compilation>
Note: X in the above code corresponds to the version number of Essential Studio that you are
currently using.
3. Register the handlers under the <httpHandlers> and <handlers> tags in
the Web.config file by using the code below.
[Web.config]
<system.web>
<httpHandlers>
<add verb="GET,
HEAD" path="MvcResourceHandler.axd"type="Syncfusion.Mvc.Shared.MvcResou
rceHandler, Syncfusion.Shared.Mvc, Version=x.x445.x.xx,
Culture=neutral, PublicKeyToken=3d67ed1f87d44c89"validate="false"/>
</httpHandlers>
</system.web>
<system.webServer>
<handlers>
<remove name="MvcResourceHandler"/>
<add verb="GET,
HEAD" name="MvcResourceHandler"path="MvcResourceHandler.axd" type="Sync
fusion.Mvc.Shared.MvcResourceHandler, Syncfusion.Shared.Mvc,
Version=x.x445.x.xx, Culture=neutral,
PublicKeyToken=3d67ed1f87d44c89"/>
</handlers>
</system.webServer>
Syncfusion.Mvc.Grid
Syncfusion.Mvc.Shared
[Web.config]
<system.web.webPages.razor>
<pages pageBaseType="System.Web.Mvc.WebViewPage">
<namespaces>
<add namespace="Syncfusion.Mvc.Shared"/>
<add namespace="Syncfusion.Mvc.Grid"/>
</namespaces>
</pages>
</system.web.webPages.razor>
Add the StyleManager extension method in the head element of the view pages (in most cases,
it is reasonable to call it within the _Layout.cshtml ).
[cshtml]
@{Html.Syncfusion().StyleManager()
.Register(stylesheets =>
{
stylesheets.Add(ComponentType.Grid);
}).Render();}
The ScriptManager() method should be placed after all of the components on the page.
Generally, this method can be used at the end of the Layout.cshtml page.
[Razor]
<body>
. . .
@{Html.Syncfusion().ScriptManager().Render();}
</body>
Note: Add this ScriptManager() at the end of <body> tag. Don’t add this in the top of
the <body> tag.
[Razor]
@model IEnumerable<MvcSampleApplication.Models.Order>
@{
Html.Syncfusion().Grid<MvcSampleApplication.Models.Order>("SampleGrid")
.Datasource(Model)
.Caption("Orders")
.Column(col =>
{
col.Add(c => c.OrderID);
col.Add(c => c.EmployeeID);
col.Add(c => c.CustomerID);
col.Add(c => c.OrderDate);
col.Add(c => c.ShipCountry);
col.Add(c => c.Freight);
})
.EnablePaging()
.EnableSorting()
.EnableGrouping()
.EnableFiltering()
.Render();
}
5. Add two methods in the HomeController (one for loading the view and one for handling
the grid
paging and sorting actions).
Controller
/// <summary>
/// Used to bind the grid.
/// </summary>
/// <returns>View page, displays the grid.</returns>
/// <summary>
/// Paging and sorting requests are mapped to this method. This
/// method invokes the HtmlActionResult from the grid. The
required
/// response is generated.
/// </summary>
/// <param name="args">Contains paging properties.</param>
/// <returns>
/// HtmlActionResult, returns the data displayed in the grid.
/// </returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data
= new NorthwindDataContext().Orders.ToList();
return data.GridActions<Order>();
<body>
….
@{Html.Syncfusion().ScriptManager().Render();}
</body>
2. Add scripts
Add the necessary script file.
Using ASPX code
Place the scripts in the Site.Master page as given in the following code:
<head runat="server">
<script src="@Url.Content("~/Scripts/jquery-1.7.min.js")"
type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/MicrosoftAjax.js") "
type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/MicrosoftMvcValidation.debug.js")"
type="text/javascript"></script>
</head>
Culture=neutral, PublicKeyToken=3d67ed1f87d44c89"/>
<add assembly="Syncfusion.Linq.Base, Version=x.x040.x.x, Culture=neutral,
PublicKeyToken=3d67ed1f87d44c89" />
<add assembly="Syncfusion.Theme.Base, Version=x.x040.x.x,
Culture=neutral, PublicKeyToken=3d67ed1f87d44c89" />
.. .
. . .
</compilation>
...
</system.web>
Note: There will be two web.config files. Place the namespace in the web.config file in the Views
folder.
For ASPX engine place the namespace in Root > web.config file.
<pages>
<namespaces>
. . .
<add namespace="Syncfusion.Mvc.Shared"/>
<add namespace="Syncfusion.Mvc.Grid"/>
. . .
</namespaces>
</pages>
5. Register the handlers under <httphandlers>, <handlers> tags in the web.config file
The following code illustrates this:
<system.web>
<httpHandlers>
<add verb="GET, HEAD" path="MvcResourceHandler.axd"
type="Syncfusion.Mvc.Shared.MvcResourceHandler, Syncfusion.Shared.Mvc,
Version=x.x340.x.x, Culture=neutral,
PublicKeyToken=3d67ed1f87d44c89" validate="false"/>
</httpHandlers>
</system.web>
<system.webServer>
<handlers>
<remove name="MvcResourceHandler"/>
<add verb="GET, HEAD" name="MvcResourceHandler"
path="MvcResourceHandler.axd"
type="Syncfusion.Mvc.Shared.MvcResourceHandler, Syncfusion.Shared.Mvc,
Version=x.x340.x.x, Culture=neutral,
PublicKeyToken=3d67ed1f87d44c89"/>
</handlers>
</system.webServer>
$.ajax({
type: 'post',
url: "Home/JQueryAjaxAction",
datatype: 'html',
success: function (data) {
$("#JQueryAjaxLoadingSyncfusionGrid")[0].innerHTML = data;
$.fn.sfEvalScripts(data);
}
});
292. Grid Invisibility Issue may occur, when using Ajax.BeginForm. To avoid this issue, use
the Ajax.BeginFormExt instead. The following code illustrates this:
[ASPX]
[Razor]
[C#]
// For UploadBox
.uploadbox .sf_uploadinput
{
z-index: 9999 !important;
}
[C#]
// For AutoCompleteTextBox
.Autocomplete_SuggestionList
{
z-index: 9999 !important;
}
Columns are defined in the view page. For defining columns in the controller, the grid properties
model is used.
Here the column property of the GridPropertyModel is used to define the columns.
1. Create a model in the application (refer to How to > Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. Add the following code in the Index.cshtml file to create the Grid control in the view.
View [cshtml]
@( Html.Syncfusion().Grid<Editing.Models.EditableOrder>("Orders_Grid",
(GridPropertiesModel<Editing.Models.EditableOrder>)ViewData["GridModel"]))
4. Create a GridPropertiesModel in the Index method. Assign columns to the grid using
the columns property in this model and set other properties of the model, then pass the
model from controller to view using the ViewData class as shown below:
/// <summary>
/// Used for rendering the grid initially.
/// </summary>
/// <returns>View page, it displays the grid.</returns>
/// <summary>
/// Used for rendering the grid initially.
/// Columns are defined in GridPropertiesModel.
/// </summary>
/// <returns>View page, it displays the grid.</returns>
public ActionResult Index()
{
var model = new GridPropertiesModel<EditableOrder>
{
Caption = "Order",
AllowPaging = true,
AllowSorting = true,
Filters = new GridFiltering
{
AllowFiltering = true,
FilterMode = FilterMode.Default,
},
AutoFormat = Skins. Office2007Blue,
Height = 500,
DataSource = OrderRepository.GetAllRecords()
};
model.Columns = new List<GridColumn<EditableOrder>>
{
new GridColumn<EditableOrder>
{
HeaderText = "Order ID",
MappingName = "OrderID",
ColumnType=typeof(int)
},
new GridColumn<EditableOrder>
{
HeaderText = "Customer ID",
MappingName = "CustomerID",
ColumnType=typeof(string)
},
new GridColumn<EditableOrder>
{
HeaderText = "Employee ID",
MappingName = "EmployeeID",
ColumnType=typeof(int)
},
new GridColumn<EditableOrder>
{
HeaderText = "Order Date",
MappingName = "OrderDate",
Format =
"{OrderDate:MM/dd/yyyy}",
ColumnType=typeof(DateTime?)
},
new GridColumn<EditableOrder>
{
HeaderText = "Freight",
MappingName = "Freight",
ColumnType=typeof(decimal)
},
};
ViewData["GridModel"] = model;
return View();
}
5. In order to work with paging or sorting actions, create a Post method for Index actions
and bind the data source to the grid as shown in the following code:
Controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
You can follow these steps to overcome this “Registering style sheet for the Grid failed because
assembly does not exist” error,
Syncfusion.Theme.Base
2. Add the following assembly to the Web.config page under the <compilation> tag.
Syncfusion.Theme.Base
The following code example shows how to add this assembly in Web.config page:
[Web.config]
<system.web>
<compilation debug="true" targetFramework="4.0">
<assemblies>
<add assembly="Syncfusion.Theme.Base, Version=10.404.0.53,
Culture=neutral, PublicKeyToken=3d67ed1f87d44c89"/>
</assemblies>
</system.web>
Option 1:
1. Click explore sample in Dashboard and open the Grid samples project.
2. Check the connection string instance in Web.config file. The current database instance can be
found using VS2010 as follows.
[Tools] -> [Options] -> [Database Tools] -> [Data Connections] - "Sql Server Instance Name
(blank for default):"
For example:
“Data Source=.\SQLEXPRESS”
Note: You can change the instance based on your database configuration.
Option 2:
If Option 1 does not resolve your issue, then create a new database for your sql server
configuration from current database based on scripting concept. Refer the following link to
generate database.
http://blog.sqlauthority.com/2011/05/07/sql-server-2008-2008-r2-create-script-to-copy-database-
schema-and-all-the-objects-data-schema-stored-procedure-functions-triggers-tables-views-
constraints-and-all-other-database-objects/
1.You have to set UnobtrusiveJavaScriptEnabled as “True” in the appSettings, its default value is
“False”.
[Web.config]
<appSettings>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
</appSettings>
View [cshtml]
<head>
<script src="@Url.Content("~=""/Scripts/jquery.validate.min.js")"
type="text/javascript"></script>
<script
src="@Url.Content("~=""/Scripts/jquery.validate.unobtrusive.min.js")"
type="text/javascript"></script>
View [cshtml]
@Html.ValidationSummary(true)
<script type="text/javascript">
function Refresh() {
var gridobj = $find("SampleGrid");
// “SampleGrid” is the ID of the Grid
gridobj.sendRefreshRequest();
}
</script>
@(Html.Syncfusion().Grid<EditableOrder>("OrdersGrid")
.Datasource(Model)
.Caption("Orders")
.ClientSideEvents(e => e.OnToolbarClickEvent("OnToolbarClickEvent"))
// ToolbarClick event
.ToolBar(tools =>
{
.Add("Custom", " GetSelectedRecord","Custom"); // add Custom Toolbar
button
}))
2. Create ToolbarClick event to get the selected records and pass the records to server using
Ajax post.
[JavaScript]
<script type="text/javascript">
var gridObj = null;
function OnToolbarClickEvent(sender, args) {
gridObj = sender;
if (args._currentItemIndex == 3) {
// Check index for "toolbarButton"
var selectedItems = sender._selectionManager.selectedRowsCollection;
// Get selected records
sender.setJSONRecord();
var value = sender.jsonrecord;
// Set JSON record to get values of selected row
if (sender.jsonrecord.length == 0) {
alert("Please select a record.")
}
var record = { CustomerID: sender.jsonrecord[0].CustomerID,
Freight: sender.jsonrecord[0].Freight,
OrderID: sender.jsonrecord[0].OrderID,
ShipCity: sender.jsonrecord[0].ShipCity,
ShipCountry: sender.jsonrecord[0].ShipCountry
};
// Pass selected records through ajax post to server side
var json = Sys.Serialization.JavaScriptSerializer.serialize(record);
try {
$.ajax({
url: "/Home/Custom",
type: 'POST',
async: false,
contentType: 'application/json; charset=utf-8',
data: json,
dataType: 'html', // <-- to expect an html response
success: function (result) {
try{
$("#gridContainer").html(result);
} catch (ex) {
console.info('The Syncfusion scripts could not be evaluated.');
}
},
error: function (err) {
console.info(err.Message);
}
});
} catch (ex) {
alert("Error: " + ex.Message);
}
}
}
</script>
[Controller]
public JsonResult Custom(string CustomerID, string OrderID, string
ShipCity, string ShipCountry, string Freight ) {
// Selected row column values are mapped here
return Json(string.Empty, JsonRequestBehavior.AllowGet);
}
View[Java Script]:
You can follow these steps to avoid “Check whether the grid post action is defined in controller”
error,
View[cshtml]:
@{
Html.Syncfusion().Grid<MvcApplication.Models.EditableOrder>("GridSrc")
.Datasource(Model)
.Caption("Order Grid")
.Column(column =>
{
column.Add(p => p.OrderID).HeaderText("Order ID").Width(90)
.TextAlign(TextAlignment.Right);
column.Add(p => p.EmployeeID).HeaderText("Employee ID").Width(90)
.TextAlign(TextAlignment.Right);
column.Add(p => p.CustomerID).HeaderText("Customer ID").Width(90);
column.Add(p => p.OrderDate).HeaderText("Order Date").Width(90);
column.Add(p => p.Freight).HeaderText("Freight")
.TextAlign(TextAlignment.Right).Format("{0:C}").Width(85);
})
.EnablePaging()
.ToolBar(tools =>
{
tools.Add(GridToolBarItems.AddNew)
.Add(GridToolBarItems.Edit)
.Add(GridToolBarItems.Delete)
.Add(GridToolBarItems.Update)
.Add(GridToolBarItems.Cancel);
})
.Mappers(mapper =>
{
mapper.InsertAction("AddOrder")
.SaveAction("OrderSave")
.DeleteAction("DeleteOrder");
})
.AutoFormat(Skins.Marble)
.Editing(edit =>
{
edit.AllowEdit(true)
.AllowNew(true)
.AllowDelete(true);
edit.EditMode(GridEditMode.Normal);
edit.PrimaryKey(key => key.Add(p => p.OrderID));
})
.Render();
}
[Controller]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult OrderSave(EditableOrder ord)
{
// Repository action method Update used to update the records into the
data source.
OrderRepository.Update(ord);
// After saving the records into the data source, refresh the grid.
var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddOrder(EditableOrder ord)
{
// Repository action method Add is used for inserting records into the
data source.
OrderRepository.Add(ord);
// After adding the record into the database, refresh the grid.
var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult DeleteOrder(int OrderID)
{
// Repository action Delete() deletes the given primary value record
from the data source.
OrderRepository.Delete(OrderID);
// After deleting, refresh the grid.
var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}
View[cshtml]
@{ Html.Syncfusion().Grid<AutoFormatting>("FormatGrid")
.Datasource(Model)
.ShowCaption(false)
.ShowRowHeader(false)
.AutoFormat(Skins.Sandune)
column.Add(c=>c.Dates).HeaderText("Dates").Format("{0:MM/dd/yyyy
hh:mm:ss}");
column.Add(c=>c.Telephone).HeaderText("Telephone").Format("{0:1 - (###)
###-####}");
}).Render();
View[Cshtml]:
@{
Html.Syncfusion().Grid<SyncfusionMvcGridApp.Models.TestModel>("Grid")
.Datasource(Model)
…
.ShowRowHeader(false)
}
View[cshtml]
@(Html.Syncfusion().Grid<Student>("OrdersGrid")
.Datasource(Model)
.Caption("Student")
.Column(column =>
{
column.Add(c=>c.UniversityCode).HeaderText("University
Code").TextAlign(TextAlignment.Right).Width(110);
column.Add(c => c.Title).Visible(false).HeaderText("Title");
column.Add(c=>c.CourseFees).Visible(false).HeaderText("Course
Fees").TextAlign(TextAlignment.Right).Width(90).Format("{CourseFees:c}"
);
column.Add(c=>c.CGPA).HeaderText("CGPA").TextAlign(TextAlignment.Right)
.Width(80);
column.Add(c=>c.Duration).HeaderText("Duration").TextAlign(TextAlignmen
t.Right).Width(80);
})
.EnablePaging()
.EnableSorting()
.EnableGrouping()
.AutoFormat(Skins.Marble)
.ToolBar(toolbar =>
{
toolbar.Add(GridToolBarItems.ExcelExport, "Excel Export");
})
.Mappers(map =>
{
map.ExportExcelAction("ExportToExcel");
}))
1. Specify the file name and Excel version details in the ExportToExcel() method and you have
to set the isVisibleColumnExt property to True for export visible columns only.
[Controller]
View[cshtml]:
@{Html.Syncfusion().Grid<EditingSample.Models.EditableOrder>("Grid")
.Datasource(Model)
.Caption("Orders")
.Column(col =>
{
col.Add(p => p.OrderID);
col.Add(P => P.CustomerID).AllowSorting(false);
col.Add(p => p.ShipCountry).AllowSorting(false);
col.Add(p => p.ShipCity);
})
.EnableSorting()
.Render();
}
View[ASPX]:
<%=Html.Syncfusion().Grid<EditingSample.Models.EditableOrder>("Grid")
.Datasource(Model)
.Caption("Orders")
.Column(col =>
{
col.Add(p => p.OrderID);
col.Add(P => P.CustomerID).AllowSorting(false);
col.Add(p => p.ShipCountry).AllowSorting(false);
View[cshtml]
View[cshtml]:
@{ Html.Syncfusion().Grid<SyncGrid.Models.Order>("GridOrder")
.Datasource(Model)
.Caption("Orders")
.Column(column => {
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.EmployeeID).HeaderText("Employee ID");
column.Add(p => p.CustomerID).HeaderText("Customer ID");
column.Add(p => p.OrderDate).HeaderText("Order
Date").Format("{OrderDate:MM/dd/yyyy}");
column.Add(p => p.Freight).HeaderText("Freight");
})
.EnablePaging()
.ToolBar(tools =>
{
tools.Add("SelectedOrders", "Selected Orders", "SelectedOrderItem");
})
.ClientSideEvents(e =>
{
e.OnToolbarClickEvent("toolbarClickEvent");
})
.Render();
}
1. You can get the selected rows from the selectedRows () method in the client side. Then, you
have to serialize the selected records and pass to the controller action.
View[Java Script]:
<script type='text/javascript'>
var selectedRecords = [];
function toolbarClickEvent(sender, args) {
var gridObj = sender;
var value = gridObj.selectedRows();
var record = null;
$.each(value, function (index, val) {
record = new Syncfusion.Mvc.Grid.SelectionEventArgs({ row: val },
gridObj.get_VisibleColumnName()).record;
selectedRecords.push(record);
});
var form = $("<form method='post' action='/Home/SelectedOrders'>
</form>").append("<input name='orders' value='" +
Sys.Serialization.JavaScriptSerializer.serialize
(selectedRecords) + "'/>")
form.appendTo(document.body);
form.submit();
}
</script>
2. In the controller, you get the serialized selected records by the SelectedOrders action and you
have to deserialize the records and pass it to another view page.
[Controller]:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult SelectedOrders(string orders)
{
var data1 = new JavaScriptSerializer().Deserialize(orders,
typeof(IEnumerable<Order>));
ViewData["OrdersMsg"] = orders;
return View("SelectedOrders", data1);
}
View[Cshtml]:
@model IEnumerable<SyncGrid.Models.Order>
<table>
<tr>
<th>Customer ID</th>
<th>Order Date</th>
<th>Freight</th>
</tr>
@foreach (var item in Model) {
<tr>
<td>@Html.DisplayFor(modelItem => item.CustomerID)</td>
<td>@Html.DisplayFor(modelItem => item.OrderDate)</td>
<td>@Html.DisplayFor(modelItem => item.Freight)</td>
</tr>
}
</table>
View[cshtml]:
@{Html.Syncfusion().Grid<MvcSampleApplication.Models.EditableOrder>("Gr
id")
.Datasource((IEnumerable<MvcSampleApplication.Models.EditableOrder>)Vie
wData["Datasrc"]).Column(cols =>
{
cols.Add(c => c.OrderID);
cols.Add(c => c.ShipCity);
cols.Add(c => c.ShipCountry);
cols.Add(c => c.Freight);
cols.Add(c => c.CustomerID);
})
.EnablePaging()
.QueryCellInfo(
cell => Html.RenderAction("onQueryCellAction", "Home", new { args =
cell })) .Render();
}
2. You have to set the tooltip for the grid cell using QueryCellInfo as illustrated in the following
code example.
[Controller]
3. If you are using Filtering/Sorting/Paging actions.You have to rebind the Querycellinfo property
again to the Grid in the post action,
[Controller]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
List<EditableOrder> data =
OrderRepository.GetAllRecords().Take(10).ToList();
var engine = data.GridActions<EditableOrder>() as
GridHtmlActionResult<EditableOrder>;
engine.GridModel.QueryCellInfo = onQueryCellAction;
return engine;}
View[cshtml]
@{Html.Syncfusion().Grid<MvcSampleApplication.Models.EditableOrder>("En
tityGrid")
.ActionMode(Syncfusion.Mvc.Grid.ActionMode.JSON)
.Column(cols =>
{
cols.Add(c => c.OrderID);
cols.Add(c => c.ShipCity);
cols.Add(c => c.ShipCountry);
cols.Add(c => c.Freight);
cols.Add(c => c.CustomerID);
})
.EnablePaging()
.EnableGrouping()
.EnableSorting()
.ClientSideEvents(events =>
{
events.QueryCellInfo("QueryCellInfoHandler");
})
.Render();
}
2. In the view, you have to create the QueryCellInfo Client-Side event and set the tooltip for grid
cell on the client side. Refer the following code example to create QueryCellInfo.
<script type="text/javascript">
function QueryCellInfoHandler(sender, args) {
if (args.Element.className == "RowCell")
$(args.Element).attr('Title', args.Text);
}
</script>
[Controller]
2. In the view, you can use Html.Renderaction in QueryCellInfo() to render the result directly.
View[cshtml]
@{
Html.Syncfusion().Grid<EditingSample.Models.EditableOrder>("SampleGrid"
)
.Datasource(Model)
.Caption("Orders")
.Column(col =>
{
col.Add(p => p.OrderID);
col.Add(p => p.EmployeeID);
col.Add(P => P.CustomerID);
col.Add(p => p.ShipCountry);
col.Add(p => p.Freight);
})
.QueryCellInfo(
cell => Html.RenderAction("onQueryCellAction", "GridBuilder", new {
args = cell }) //Action name, controller name and cell
)
.EnablePaging()
.EnableSorting()
.Render(); }
3. To make it work with paging and sorting actions, create a Post method for Index actions and
bind the data source to the grid as shown in the following code example.
[Controller]
[Cshtml]
<div>
<p style="color: Red;">
Select any row and click Up/Down Arrows to move row</p>
<p style="color: Red;">
Click save to store position of the records on database</p>
<img src="../../Content/Up.png" class="UpRows" />
<img src="../../Content/Down.png" class="DownRows" />
<img src="../../Content/save.png" class="SaveOrders" />
</div>
@(Html.Syncfusion().Grid<Customer>("TestGrid")
.Caption("Employee Grid")
.Datasource(Model)
.Column(column =>
{
column.Add(p => p.CustomerID);
column.Add(p => p.CompanyName);
column.Add(p => p.ContactName);
column.Add(p => p.Address);
})
.ClientSideEvents(events=>events.OnActionSuccess("Paging"))
.EnablePaging())
2.In load event, set rowIndex of table ‘tr’ to data attribute as index.
Sys.Application.add_load(function () {
$("#TestGrid_Table").find('tr').each(function () {
$(this).data("index", ($(this)[0].rowIndex + 1));
});
var order = new Array();
});
3.Using SelectedRowsCollection, you can retreive the selected records from GridObject and
parse the selectedrow index to move up or down the rows.Using selectedrow index, the record
cells can be moved Up or Down except in the first column cells.
[JavaScript]:
Sys.Application.add_load(function () {
var gridObj = $find("TestGrid");
var order = new Array();
$('.DownRows').click(function () {
var Index = gridObj._selectionManager.selectedRowsCollection;
DownRows($("#TestGrid_Table").find('tr')[parseInt(Index)]);
gridObj._selectionManager.deselectRow(parseInt(Index) + 1);
gridObj._selectionManager.selectRow(parseInt(Index));
});
$('.UpRows').click(function () {
var gridObj = $find("TestGrid");
var Index = gridObj._selectionManager.selectedRowsCollection;
UpRows($("#TestGrid_Table").find('tr')[parseInt(Index)]);
gridObj._selectionManager.deselectRow(parseInt(Index) - 1);
gridObj._selectionManager.selectRow(parseInt(Index));
});
});
function UpRows(row) {
var prevRow = row.previousSibling;
if (prevRow) {
var index = $(prevRow).data('index');
$(PrevSiblings).insertAfter($(row).find("td[class*='RowCell']").eq(0));
$(CurrentSiblings).insertAfter($(prevRow).find("td[class*='RowCell']").
eq(0);
$(row).data('index', $(row).data('index'));
$(prevRow).data('index', index);
}
}
function DownRows(row) {
var nextRow = row.nextSibling;
if (nextRow) {
var index = $(nextRow).data('index');
// first columns cells excluded here is optional
var NextSiblings = $(nextRow).find("td[class*='RowCell']").slice(1);
var CurrentSiblings = $(row).find("td[class*='RowCell']").slice(1);
$(NextSiblings).insertAfter($(row).find("td[class*='RowCell']").eq(0));
$(CurrentSiblings).insertAfter($(nextRow).find("td[class*='RowCell']").
eq(0);
$(row).data('index', $(row).data('index'));
$(nextRow).data('index', index);
}
}
[CSS]
.HeaderCell .FilterIcon
display:none !important;
[CSS]
<style type="text/css">
.Syncfusion-Grid-Core .RowCell, .Syncfusion-Grid-Core .EmptyCell,
.Syncfusion-Grid-Core tr[class*="ChildRow"] > .ChildGrid
{
line-height: 3.3em!important;
}
</style>
View [cshtml]
@{Html.Syncfusion().Grid<JSONOrder>("SampleGrid")
.Datasource(Model)
.Caption("Orders")
[Controller]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = GridOrders;
var engine = data.GridActions<JSONOrder>() as GridHtmlActionResult<JSON
Order>;
engine.GridModel.QueryCellInfo = onQueryCellAction;
return engine;
}
public void onQueryCellAction(GridTableCell<JSONOrder> args)
{
if (args.TableCellType == GridTableCellType.RecordFieldCell ||
args.TableCellType == GridTableCellType.AlternateRecordFieldCell)
{
if (args.Column.MappingName == "EmployeeID")
{
args.Text = "<a class='TemplateCell'
href='Home/Load?id="+args.Data.OrderID+"'>" + args.Data.EmployeeID +
"</a>";
}
1. Configure a grid and enable the custom binding mode using EnableOnDemand property.
3. Add GroupDescriptors for initial grouping. Refer the following code example:
[Controller]
public ActionResult Index()
{
var model = GetGridPropertiesModel(0);
return View(model);
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
var data = UserModel.GetUsersPage(args.StartIndex);
return data.GridActions<ExportUserObject>();
}
private static GridPropertiesModel<ExportUserObject>
GetGridPropertiesModel
(int startIndex)
{
var totalCount = 0;
var data = UserModel.GetUsersPage(startIndex, ref totalCount);
var model = new GridPropertiesModel<ExportUserObject>
{
DataSource = data,
Caption = "Users",
AllowPaging = true,
AllowSorting = true,
AllowGrouping=true,
TotalRecordsCount = totalCount,
PageSetting = new PageSettings()
{
AllowPaging = true,
PageSize = Constants.PageSize,
PageCount = Constants.PageCount,
CurrentPage = 1,
},
EnableOnDemand = true,
};
//Group by the first name.
model.GroupDescriptors.Add("FirstName");
return model;
}
2. To activate the alternate row color feature in the view, set the .EnableAlternateRowStyling()
property.
View[cshtml]
@( Html.Syncfusion().Grid<Order>("Grid")
.Datasource(Model)
.Caption("Orders")
.EnableAlternateRowStyling()
.EnablePaging()
.AutoFormat(Skins.Sandune)
.Column( columns => {
columns.Add(p => p.OrderID).HeaderText("Order ID");
columns.Add(p => p.CustomerID).HeaderText("Customer ID");
columns.Add(p => p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship Country");
columns.Add(p => p.ShipCity).HeaderText("Ship City");
}) )
[CSS]
<style type="text/css">
.Summary
text-align:right!important;
</style>
2. Set text-align to left for the specific Summary row cells (first cell) in Client-Side OnLoad event.
[JavaScript]
<script type="text/javascript">
function load(sender, args) {
var context = $find('Summary_Grid'); // Find the gridobject
var GridSummary = $(context.get_element()).find('table.GridSummary');
if (GridSummary.length > 0) {
var GridSummaryTR = $(GridSummary[0]).find('tr');
for (var i = 0; i < GridSummaryTR.length; i++) {
varGridSummaryCol=$(GridSummaryTR[i]).children('td.Summary:eq(1)').css(
'cssText', 'text-align: left !important')
}
}
}
</script>
AllowFiltering=true,
FilterMode = FilterMode.Default,
AllowFormatFiltering=true,
};
5.36 How to: Add New, Delete and Update multiple grids
uing external button
You can follow these steps to add new, delete and update multiple grids uing external button.
1. Create a Grid control in the view and configure its properties.
View[Grid.Cshtml]
Grid1:
@{Html.Syncfusion().Grid<EditingSample.Models.EditableOrder>("SampleGri
d")
.Datasource(Model)
.ActionMode(ActionMode.JSON)
.Caption("Orders")
.Column(col =>
{
col.Add(p => p.OrderID);
col.Add(P => P.CustomerID);
col.Add(p => p.ShipCountry);
col.Add(p => p.ShipCity);
})
.PageSettings(page => { page.PageSize(7); })
.EnablePaging()
.ToolBar(
tool =>
{
tool.Add(GridToolBarItems.AddNew);
tool.Add(GridToolBarItems.Edit);
tool.Add(GridToolBarItems.Delete);
tool.Add(GridToolBarItems.Update);
tool.Add(GridToolBarItems.Cancel);
}
)
.Mappers(map =>
{
map.Action("ServerPaging")
.SaveAction("BulkSave");
})
.Editing(edit =>
{
edit.AllowEdit(true)
.AllowNew(true)
.AllowDelete(true);
edit.EditMode(GridEditMode.ManualExcel);
edit.PrimaryKey(key => key.Add(p => p.OrderID));
})
.Render();
}
Grid2:
@{Html.Syncfusion().Grid<EditingSample.Models.EditableOrder>("SampleGri
d1")
.Datasource(Model)
.ActionMode(ActionMode.JSON)
.Caption("Orders")
.Column(col =>
{
col.Add(p => p.OrderID);
col.Add(P => P.CustomerID);
col.Add(p => p.ShipCountry);
col.Add(p => p.ShipCity);
})
.PageSettings(page => { page.PageSize(7); })
.EnablePaging()
.ToolBar(
tool =>
{
tool.Add(GridToolBarItems.AddNew);
tool.Add(GridToolBarItems.Edit);
tool.Add(GridToolBarItems.Delete);
tool.Add(GridToolBarItems.Update);
tool.Add(GridToolBarItems.Cancel);
}
)
.Mappers(map =>
{
map.Action("ServerPaging")
.SaveAction("BulkSave1");
})
.Editing(edit =>
{
edit.AllowEdit(true)
.AllowNew(true)
.AllowDelete(true);
edit.EditMode(GridEditMode.ManualExcel);
edit.PrimaryKey(key => key.Add(p => p.OrderID));
})
.Render();
}
2. Create a button element in the view page and refer the following code example for the button
click event.
View[Grid.Cshtml]
<input type="button" value="Add" id="Add" name="Add" />
<input type="button" value="Edit" id="Edit" name="Edit" />
<input type="button" value="Delete" id="Delete" name="Delete" />
<input type="button" value="Save" id="Save" name="Save" />
<input type="button" value="Cancel" id="Cancel" name="Cancel" />
<script type="text/javascript">
$('#Add').bind('click', function () {
2.In the controller, create a method to save changes. Following code example shows how to
create the repository method BulkSave() to update records to the data source.
[Controller]
[AcceptVerbs(HttpVerbs.Post)]
Public ActionResult BulkSave([Bind(Prefix =
"updatedRecords")]IEnumerable<EditableOrder> orders, [Bind(Prefix =
"addedRecords")]IEnumerable<EditableOrder> addRcrds, [Bind(Prefix =
"deletedRecords")]IEnumerable<EditableOrder> delRcrds)
{
//Repository action method Update used to update the records into
datasource.
if (orders != null)
OrderRepository.Update(orders);
if (addRcrds != null)
OrderRepository.Add(addRcrds);
if (delRcrds != null)
OrderRepository.Delete(delRcrds);
//After saving the records into datasource, refresh the grid
var data = OrderRepository.GetAllRecords();
return data.GridJSONActions<EditableOrder>();
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult BulkSave1([Bind(Prefix =
"updatedRecords")]IEnumerable<EditableOrder> orders, [Bind(Prefix =
"addedRecords")]IEnumerable<EditableOrder> addRcrds, [Bind(Prefix =
"deletedRecords")]IEnumerable<EditableOrder> delRcrds)
{
//Repository action method Update used to update the records into
Datasource.
if (orders != null)
OrdersData.Update1(orders);
if (addRcrds != null)
OrdersData.Add1(addRcrds);
if (delRcrds != null)
OrdersData.Delete(delRcrds);
//After saving the records into datasource refresh the grid
var data = OrdersData.GetAllRecords();
return data.GridJSONActions<OrderEdit>();
[View]
View[cshtml]
@{ Html.Syncfusion().Grid<Sample.Models.EditableOrder>("OrderGrid")
.Datasource(Model)
.ActionMode(ActionMode.JSON)
.Caption("Orders")
.Column(col =>
{
2. In client side, select “ShipCity” cell and replace it with textbox with the cellvalue only if the
CustomerID is equal to “VINET”.
<script type="text/javascript">
function onCellEdit(sender, args) {
if (args.colObj.Name == "ShipCity") {
if (sender._currentDataItem.CustomerID == "VINET") {
$(sender._editTD).find("select#ShipCity").replaceWith('<input
type="text" value="' + sender._currentDataItem.ShipCity + '"
name="ShipCity" id="ShipCity" data-val-length-max="15" data-val-
length="ShipCity must be 15 characters." data-val="true">');
}
}
}
</script>
View [cshtml]
@{
Html.Syncfusion().Grid<MvcSampleBrowser.Models.EditableOrder>("GridSrc"
)
.Datasource(Model)
.Column(column =>
{
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.CustomerID).HeaderText("Customer ID");
column.Add(p => p.ShipCountry).HeaderText("Ship Country");
})
.ClientSideEvents(eve =>
{
eve.OnRecordExpanding("OnExpanding");
eve.OnLoad("success");
eve.OnActionSuccess("success");
})
.ChildGrid(child =>
{
child.ChildGridTemplate(Html.Syncfusion().Grid<
OrderDetailEdit>("ChildGrid_${OrderID}")
.Caption("OrderDetails Grid")
.Column(c =>
{
c.Add(p => p.OrderID).HeaderText("Order ID");
c.Add(p => p.ProductID).HeaderText("Product ID");
c.Add(p => p.UnitPrice).HeaderText("Unit Price");
})
.ToChildGridTemplate());
})
.Render();
}
[JavaScript]
<script type="text/javascript">
function success(sender, args) {
var array = ["10251", "10252", "10258"]; // list of primary keys to
hide/ expand/collapse.
var trs = $("#" + sender.get_element().id + "_Table tr");
$.each(array, function (index, val) {
$(trs).find("td:contains(" + val +
")").parent().find("td.MasterCellCollapse div").css("background-image",
"none");
});
}
function OnExpanding(sender, args) {
var array = ["10251", "10252", "10258"]; // list of primary keys to
hide/ expand/collapse
var trs = $("#" + sender._ID + "_Table tr");
$.each(array, function (val) {
if (args.data.OrderID == array[val]) {
args.cancel = true;
$(trs).find("td:contains("+args.data.OrderID+")").parent().find("td.Mas
terCellCollapse div").css("background-image", "none");
}
});
}
</script>
View [Cshtml]
@{
Html.Syncfusion().Grid<SyncfusionMvcGridApp.Models.TestModel>("Grid")
.Datasource(Model)
.EnableGrouping()
.Grouping(group => { group.ShowGroupDropArea(false); })
}
View [ASPX]
<%=
Html.Syncfusion().Grid<SyncfusionMvcGridApp.Models.TestModel>("Grid")
.Datasource(Model)
.EnableGrouping()
.Grouping(group => { group.ShowGroupDropArea(false); })
%>
View[cshtml]
@{Html.Syncfusion().Grid<EditableOrder>("SampleGrid")
.ActionMode(ActionMode.Server)
.Datasource(Model)
.Caption("Orders")
.Column(col =>
{
col.Add(c => c.OrderID);
col.Add(c => c.EmployeeID);
2.Populate external country list for the dropdown values and return the values as JSON from the
GetCountries() method.
[Controller]
3. In the OnActionBegin event you get the countries list from GetCountries method using $.ajax
and assign the value to dropDownOptions variable. In the OnActionSuccess event, you can
append the country list items for the specified column.
[ASPX]
<script type="text/javascript">
var dropDownOptions = null;
function GetdropDownData(sender, args) {
$.ajax({
type: "POST",
url: "Home/GetCountries",
dataType: "json",
success: function (data) {
dropDownOptions = data;
}
});
}
function SetdropDownData(sender, args) {
if (dropDownOptions != null)
UpdateDropDown(dropDownOptions);
}
function UpdateDropDown(data) {
$("#ShipCountry").empty();
$.each(data, function (index, val) {
var optionTag = $("<option></option>");
$(optionTag).val(val.Value).text(val.Text);
$("#ShipCountry").append(optionTag);
});
}
</script>
View [cshtml]
<input type="button" id="Button" name="Copy" value="Copy"
onclick="CopyTo()"/>
@(Html.Syncfusion().Grid<EditableOrder>("OrdersGrid")
.ActionMode(Syncfusion.Mvc.Grid.ActionMode.JSON)
.Caption("Orders")
.Column(column =>
{
column.Add(c => c.OrderID).HeaderText("Order ID");
column.Add(c => c.EmployeeID).HeaderText("Employee Id");
column.Add(c => c.ShipName).HeaderText("Ship Name");
column.Add(c => c.ShipCity).HeaderText("Ship City");
column.Add(c => c.Freight).HeaderText("Freight");
})
)
View [ASPX]
<%= Html.Syncfusion().Grid<EditableOrder>("OrdersGrid")
.ActionMode(Syncfusion.Mvc.Grid.ActionMode.JSON)
.Caption("Orders")
.Column(column =>
{
column.Add(c => c.OrderID).HeaderText("Order ID");
column.Add(c => c.EmployeeID).HeaderText("Employee Id");
View[cshtml]
@{Html.Syncfusion().Grid<EditingSample.Models.EditableOrder>("Grid")
.Datasource(Model)
.Caption("Orders")
.ActionMode(ActionMode.JSON)
.Column(col =>
{
col.Add(p => p.OrderID);
…
})
.EnablePaging()
.Render();
}
View[ASPX]
<%=Html.Syncfusion().Grid<EditingSample.Models.EditableOrder>("Grid")
.Datasource(Model)
.Caption("Orders")
.ActionMode(ActionMode.JSON)
.Column(col =>
{
col.Add(p => p.OrderID);
…
})
.EnablePaging()
.Render();
%>
2. In the view page, use a dropdown box to change the grid column values.
View[cshtml]
<select name="ShipCountry" id="ShipCountry" class="ShipCountry">
<option value="Argentina" selected="selected">Argentina</option>
<option value="Austria">Austria</option>
<option value="Belgium">Belgium</option>
<option value="Brazil">Brazil</option>
<option value="Canada">Canada</option>
<option value="Denmark">Denmark</option>
<option value="USA">USA</option>
</select>
3. In client side, get the grid contents using “get_dataSource” method in JSON mode and
process (modifying the entire column values) the data. Then, refresh the grid in client-side using
“clientSideRefresh” method.
View [Cshtml]
@{ Html.Syncfusion().Grid<TestModel>("Grid")
.ActionMode(ActionMode.Server)
.Datasource(Model)
.AutoFormat(Skins.Office2007Silver)
.Column(col =>
{
col.Add(c => c.TestId);
col.Add(c => c.Name);
})
.Editing(edit =>
{
edit.Dialog(dialog =>
{
dialog.Height(320);
dialog.Width(320);
dialog.Position(DialogPositions.Center);
dialog.Show(DialogAnimations.bounce);
dialog.Hide(DialogAnimations.fold);
});
edit.AllowEdit(true)
.AllowNew(true)
.AllowDelete(true);
edit.EditMode(GridEditMode.DialogTemplate);
edit.DialogModeEditorTemplate("EditTemplate");
View [ASPX]
<%= Html.Syncfusion().Grid<TestModel>("Grid")
.ActionMode(ActionMode.Server)
.Datasource(Model)
.AutoFormat(Skins.Office2007Silver)
.Column(col =>
{
col.Add(c => c.TestId);
col.Add(c => c.Name);
})
.Editing(edit =>
{
edit.Dialog(dialog =>
{
dialog.Height(320);
dialog.Width(320);
dialog.Position(DialogPositions.Center);
dialog.Show(DialogAnimations.bounce);
dialog.Hide(DialogAnimations.fold);
});
edit.AllowEdit(true)
.AllowNew(true)
.AllowDelete(true);
edit.EditMode(GridEditMode.DialogTemplate);
edit.DialogModeEditorTemplate("_EditTemplate");
edit.PrimaryKey(key => key.Add(c => c.TestId));
}).Render();
%>
2. Configure edit item template with model and pass values for “DropDownListFor” control.
View [Razor]
@model TestModel
<fieldset>
@Html.HiddenFor(model => model.TestId)
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.AList)
</div>
<div class="editor-field">
@Html.DropDownListFor(model => model.AListId, Model.AList)
</div>
</fieldset>
View [ASPX]
<fieldset>
<div class="editor-label">
<%= Html.LabelFor(model => model.Name) %>
</div>
<div class="editor-field">
<%= Html.TextBoxFor(model => model.Name) %>
<%= Html.ValidationMessageFor(model => model.Name) %>
</div>
<div class="editor-label">
<%= Html.LabelFor(model => model. AList) %>
</div>
<div class="editor-field">
<%= Html.DropDownListFor(model => model.AListId, Model.AList)) %>
</div>
</fieldset>
[Controller]
public ActionResult Index()
{
var modelList = TestModel.GetAll();
return View(modelList);
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args, int? TestId)
{
var modelList = TestModel.GetAll();
RequestType currentRequest =
(RequestType)Convert.ToInt32(args.RequestType);
// Check if the current request is an Edit request and if the edit mode
is
In Template form mode. Then, call the PartialView() to render the
template.
if (currentRequest == RequestType.BeginEdit)
{
View[cshtml]
@{Html.Syncfusion().Grid<Order>("Filter_Grid")
.Datasource(Model)
.Caption("Orders")
.Column(column =>
{
column.Add(p => p.OrderID).HeaderText("Order ID").AllowFilter(true)
.Width(100);
column.Add(p => p.EmployeeID).HeaderText("Employee ID").Width(110);
column.Add(p => p.CustomerID).HeaderText("Customer ID").Width(140);
column.Add(P => P.ShipCountry).HeaderText("Ship Country").Width(120);
column.Add(p => p.ShipName);
column.Add(p => p.OrderDate).HeaderText("Order Date")
.Format("{OrderDate:MM/dd/yyyy}").Width(150);
})
.EnablePaging()
.EnableFiltering()
.ClientSideEvents(eve => eve.OnActionSuccess("ActionSuccess"))
.AutoFormat(Skins.Marble)
.Render();
}
2. You can get the “CurrentFilterColumn” members from “FilteringMgr” as shown in the following
code example.
[Java Script]
<script type="text/javascript">
function ActionSuccess(sender, args) {
if (args.RequestType == "Filtering") {
var CurrentFilterColumn =
sender.FilteringMgr.get_CurrentFilterColumn().Member;
alert(CurrentFilterColumn + " column filtered");
}
}
</script>
[cshtml]
@{Html.Grid<Editing.Models.EditableOrder>("Grid1")
.Datasource((IEnumerable<Editing.Models.EditableOrder>)ViewData["data"]
)
.Column(column =>
{
column.Add(p => p.OrderID).HeaderText("Order
ID").Width(100).TextAlign(TextAlignment.Right);
column.Add(p => p.CustomerID).HeaderText("Customer ID");
column.Add(p => p.EmployeeID).HeaderText("Employee
ID").TextAlign(TextAlignment.Right).Width(110);
column.Add(p => p.ShipName).HeaderText("Ship Name");
column.Add(p => p.ShipCountry).HeaderText("Ship Country");
})
.ClientSideEvents(e => e.OnToolbarClickEvent("OnToolbarClickEvent")
.OnLoad("Load"))
.ToolBar(tools =>
{
tools.Add("Expand", "ExpandItem")
.Add("Collapse", "CollapseItem")
.Add("Refresh", "RefreshItem")
}).Render();}
[script]
function Load(sender) {
$find('Grid1').sendRefreshRequest();
}
function OnToolbarClickEvent(sender, args) {
gridObj = sender;
if (args._currentItemIndex == 0) {
sender._waiting.ShowPopUp();
$.ajax({
type: "POST",
url: "Home/AjxCall"
}).done(function () {
sender._waiting.HidePopUp();
});
}
. .. }
@(Html.Syncfusion().Grid<EditableOrder>("SampleGrid")
.Datasource((IEnumerable<EditableOrder>)ViewData["data"])
.EnablePaging()
.ActionMode(ActionMode.JSON)
.EnableSorting()
.Caption("Orders")
.Column(column =>
{
column.Add(c => c.OrderID).HeaderText("Order ID");
column.Add(c => c.EmployeeID).HeaderText("EmployeeID");
column.Add(c => c.ShipCountry).HeaderText("Ship Country");
column.Add(c => c.ShipCity).HeaderText("Ship City");
column.Add("ManageRecords", col =>
{
// Unbound column for editing records.
col.Commands(cmd =>
{
cmd.Command(CommandTypes.Edit).Text("Edit")
.ItemType(UnBoundItemTypes.HyperLink).ItemOption(UnboundItemOptions.Tex
tOnly);
});
// Unbound column for updating records.
col.Commands(cmd =>
{
cmd.Command(CommandTypes.Update).Text("Update").ItemType(UnBoundItemTyp
es.HyperLink)
.ItemOption(UnboundItemOptions.TextOnly);
});
}).UnBound(true); // Unbound is set to true to enable unbound column
})
.Mappers(mapper=>{
mapper.InsertAction("AddOrder").SaveAction("OrderSave").DeleteAction("D
eleteOrder");
})
.ToolBar(tools =>
{
tools.Add(GridToolBarItems.AddNew)
.Add(GridToolBarItems.Edit)
.Add(GridToolBarItems.Delete)
.Add(GridToolBarItems.Update)
.Add(GridToolBarItems.Cancel);
})
.Editing(edit =>
{
edit.AllowEdit(true).AllowNew(true).AllowDelete(true);
View[cshtml]
@(Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model)
.Caption("Orders")
.Column(column =>
{
column.Add(p => p.OrderID).HeaderText("Order ID").Width(100);
column.Add(p => p.CustomerID).HeaderText("Customer ID").Width(100);
column.Add(p => p.EmployeeID).NumericEditParams(e=>
e.ShowSpinButton(false));
column.Add(p => p.ShipCountry).HeaderText("Ship Country");
column.Add(p => p.ShipCity).HeaderText("Ship City");
})
.EnablePaging()
.ToolBar(tools =>
{
tools.Add(GridToolBarItems.AddNew)
.Add(GridToolBarItems.Edit)
.Add(GridToolBarItems.Delete)
.Add(GridToolBarItems.Update)
.Add(GridToolBarItems.Cancel);
})
.Mappers(mapper =>
{
mapper.InsertAction("AddOrder")
.SaveAction("OrderSave")
.DeleteAction("DeleteOrder");
})
.Editing(edit =>
{
edit.AllowEdit(true)
.AllowNew(true)
.AllowDelete(true);
edit.EditMode(GridEditMode.Normal);
edit.PrimaryKey(key => key.Add(p => p.OrderID));
}))
View [cshtml]
@(Html.Syncfusion().Grid<System.Data.DataRow>("OrdersGrid")
.Datasource(Model)
.Caption("Orders")
.Column(col =>
col.Add("OrderID", false).HeaderText("Order
ID").TextAlign(TextAlignment.Right);
col.Add("RequiredDate", false).HeaderText("Required
Date").Format("{0:MM/dd/yyyy}");
col.Add("Freight", false).Format("{0:C}").Width(100);
})
.EnablePaging()
.EnableGrouping()
@{Html.Syncfusion().Grid<EditableOrder>("Users_Grid")
.Datasource(Model)
.ShowCaption(true)
.Caption("Total")
.Column(column =>
{
column.Add(c => c.OrderID).AllowEditing(false);
column.Add(c => c.EmployeeID);
column.Add(c => c.ShipName);
column.Add(c => c.ShipCity);
column.Add(c => c.ShipCountry);
})
.PageSettings(p => p.AllowPaging(true).PageSize(10))
.QueryParam("?EmpID=" + ViewData["value"])
.AutoFormat(Skins.Marble)
.Render();
}
</div>
@{ using (Html.BeginForm("Index", "Home", FormMethod.Get))
{
<p>Enter Employee ID: </p>
@Html.TextBox("EmpID")
<input type="submit" value="submit" id="sub" />
}}
3. When Submit button is clicked, it passes the EmpID value to the controller’s get action, filters
the data, and returns the values to view.
[Controller]
4. In the post action, you can get the EmpID value from the “QueryParam” and using this value,
you can maintain filtering state after any grid actions.
[AcceptVerbs(HttpVerbs.Post)]
{
data = OrderRepository.GetAllRecords().Take(100).ToList();
}
return data.GridActions<EditableOrder>();
}
@(Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model)
.Column(column =>
{
column.Add(p=> p.OrderID).HeaderText("Order
ID").TextAlign(TextAlignment.Right).Width(100);
column.Add(p => p.CustomerID).HeaderText("Customer ID").Width(100);
column.Add(p => p.ShipCountry).HeaderText("Ship Country");
column.Add(p => p.ShipCity).HeaderText("Ship City");
column.Add(p=>p.Freight).HeaderText("Freight").Format("{0:C}")
.TextAlign(TextAlignment.Right)
.Width(100);
})
.EnablePaging()
.ToolBar(tools =>
{
tools.Add(GridToolBarItems.AddNew)
.Add(GridToolBarItems.Edit)
.Add(GridToolBarItems.Delete)
.Add(GridToolBarItems.Update)
.Add(GridToolBarItems.Cancel);
})
.Mappers(mapper =>
{
mapper.InsertAction("AddOrder")
.SaveAction("OrderSave")
.DeleteAction("DeleteOrder");
})
.Editing(edit =>
{
edit.AllowEdit(true)
.AllowNew(true)
.AllowDelete(true);
edit.EditMode(GridEditMode.Normal);
edit.PrimaryKey(key => key.Add(p => p.OrderID));
}))
2. You need to check for duplicate records in the controller mapper action method, if the record
already exists in the grid then add the error message in the response header.
[Controller]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddOrder(EditableOrder ord)
{
Var add =
OrderRepository.GetAllRecords().Where(o=>o.OrderID==ord.OrderID).
FirstOrDefault();
if (add == null)
{
OrderRepository.Add(ord);
var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}
else
{
string status = string.Empty;
status = "Duplicate Row cannot inserted";
Response.AddHeader("Status", status);
var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}
}
3. The error is passed from controller to view by using ajaxSuccess() method and displays on
the view page.
View [cshtml]
[Controller]
public ActionResult Index()
{
return View(ExcelData());
}
View[cshtml]
@model System.Data.DataTable
@{Html.Syncfusion().Grid<System.Data.DataRow>("Users_Grid")
.Datasource(Model)
.Caption("Users")
.EnablePaging()
.EnableSorting()
.Render();
}
3. To make it work with paging and sorting actions, create a Post method for Index actions and
bind the data source to the grid as illustrated in the following code example.
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
return ExcelData().AsEnumerable().GridActions<System.Data.DataRow>();
}
[Controller]
{
Created,
Commented,
UploadedFile
}
public ActionResult Index()
{
ViewData["data"] = OrderRepository.GetAllRecords();
ViewData["ShipCountry"] = this.InvestigationList;
return View();
}
View [Cshtml]
@(Html.DropDownListFor(model=>model.ShipCountry,(IEnumerable<SelectList
Item>)
ViewData["ShipCountry"])
)
[Controller]
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Index()
{
var data = new NorthwindDataContext().Orders.ToList();
return View(data);
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new NorthwindDataContext().Orders.ToList();
ActionResult result = data.GridActions<Order>();
object sort = args.SortDescriptors; // sort descriptor values
object filter = args.FilterDescriptors; // filter descriptor values
if (args.RequestType == 2)
{
System.Xml.Serialization.XmlSerializer Serialize = new
System.Xml.Serialization.XmlSerializer(sort.GetType());
XmlTextWriter XmlFilter = new
XmlTextWriter(HttpContext.Server.MapPath("SortingFilterInfoXml.xml"),
System.Text.Encoding.UTF8);
XmlFilter.Formatting = System.Xml.Formatting.Indented;
Serialize.Serialize(XmlFilter, sort);
XmlFilter.Close();
}
else if (args.RequestType == 7 && filter != null)
{
System.Xml.Serialization.XmlSerializer Serialize = new
System.Xml.Serialization.XmlSerializer(filter.GetType());
XmlTextWriter XmlFilter = new
XmlTextWriter(HttpContext.Server.MapPath("SortingFilterInfoXml.xml"),
System.Text.Encoding.UTF8); // stored in XML
XmlFilter.Formatting = System.Xml.Formatting.Indented;
Serialize.Serialize(XmlFilter, filter);
XmlFilter.Close();
}
return result;
}
View [cshtml]
[JavaScript]
<script type="text/javascript">
$(function () {
$("#Group").click(function () {
var gridObj = $find("Grid");
var visibleColumns = new Array();
$.each(gridObj.get_VisibleColumns(), function (j, value) {
visibleColumns.push(value.Name);
});
$.ajax({
type: 'post',
url: "Home/Group",
traditional: true,
dataType:'json',
data: { "GroupedColumns": gridObj.get_GroupedColumns(), "VisibleColumns":
visibleColumns }, // Pass Groupedcolumns and Visiblecolumns data
success: function (data) {
alert("Success");
}
});
});
});
</script>
3. Create an XML document. Update the grouping and column values as shown in the following
code example.
[Controller]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Group(PagingParams args, IEnumerable<string> GroupedColumns,
IEnumerable<string> VisibleColumns)
{
IEnumerable data = new NorthwindDataContext().Orders.ToList();
xmlDoc.Save(@HttpContext.Server.MapPath("~/GroupingColumnOrderInfo.xml"));
return Json(String.Empty,JsonRequestBehavior.AllowGet);
}
4. The Grid information is stored in XML. The same logic can be used for storing the information
in database too.
View [Tab]
<div id="tabContainer">
<ul>
View [Grid]
@(Html.Syncfusion().Grid<Tab.Models.Order>((string)ViewData["GridId"])
// Queryparam gridID can get the value from ViewData["GridId"]
.Datasource(Model)
.Caption("Orders")
.AutoFormat(Skins.Marble)
.Column(col =>
{
col.Add(c => c.OrderID).HeaderText("Order ID").Width(60);
col.Add(c => c.EmployeeID).HeaderText("Employee ID").Width(80);
col.Add(c => c.ShipName).HeaderText("Ship Name").Width(300);
col.Add(c => c.ShipCity).Width(175).HeaderText("Ship City").Width(100);
}))
[Controller]
View [Cshtml]
@{Html.Syncfusion().Grid<Order>("SampleGrid")
.Datasource(Model)
.Caption("Orders")
.Column(col =>
{
col.Add(c => c.OrderID).Width(200).HeaderText("OrderID");
col.Add(c => c.EmployeeID).Width(150).HeaderText("Emp ID");
col.Add(c => c.CustomerID).Width(150);
col.Add(c => c.OrderDate).Width(150);
col.Add(c => c.Freight).Width(150);
})
//Setting keyboard navigation to false.
.AllowKeyboardNavigation(false)
.Render();
}
View [ASPX]
<%= Html.Syncfusion().Grid<Order>("SampleGrid")
.Datasource(Model)
.Caption("Orders")
.Column(col =>
{
col.Add(c => c.OrderID).Width(200).HeaderText("OrderID");
View [Cshtml]
@{Html.Syncfusion().Grid<Order>("GridSrc")
.Datasource(Model)
.Caption("Order Grid")
.EnableFiltering()
.ClientSideEvents(e => e.OnActionBegin("begin"))
.Column(column =>
{
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.EmployeeID).HeaderText("Employee ID");
column.Add(p => p.CustomerID).HeaderText("Customer ID");
column.Add(p => p.ShipCountry).HeaderText("Ship Country");
column.Add(p => p.OrderDate).HeaderText("Order Date");
column.Add(p => p.Freight).HeaderText("Freight");
})
.QueryCellInfo(
cell => Html.RenderAction("onQueryCellAction", "Home", new
{ args = cell })
)
.EnablePaging()
.EnableSorting()
.EnableGrouping()
.AutoFormat(Skins.Sandune)
.Render();
}
View [ASPX]
<%Html.Syncfusion().Grid<Order>("GridSrc")
.Datasource(Model)
.Caption("Order Grid")
.EnableFiltering()
.ClientSideEvents(e => e.OnActionBegin("begin"))
.Column(column =>
{
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.EmployeeID).HeaderText("Employee ID");
column.Add(p => p.CustomerID).HeaderText("Customer ID");
column.Add(p => p.ShipCountry).HeaderText("Ship Country");
column.Add(p => p.OrderDate).HeaderText("Order Date");
column.Add(p => p.Freight).HeaderText("Freight");
})
.QueryCellInfo(
cell => Html.RenderAction("onQueryCellAction", "Home", new
{ args = cell })
)
.EnablePaging()
.EnableSorting()
.EnableGrouping()
.AutoFormat(Skins.Sandune)
.Render();
%>
View [Cshtml]
<input type="text" name="filter" id="filter" />
<input type="button" name="btn" value="filter" onclick="filter()" />
<script type="text/javascript">
function begin(sender, args) {
args.data["searchdescriptors"]=
Sys.Serialization.JavaScriptSerializer.serialize(sender._search);
}
function filter() {
var gridobj = $find('GridSrc');
var filterobj = new Array();
var searchText = $('input#filter').val();
var filterObjCustomerID = {};
var filterObjShipCountry = {};
filterObjCustomerID["Column"] = "CustomerID";
filterObjShipCountry["Column"] = "ShipCountry";
filterObjShipCountry["Operator"] = filterObjCustomerID["Operator"] =
"8";
filterObjShipCountry["Value"] = filterObjCustomerID["Value"] =
searchText;
filterObjShipCountry["Predicate"] = filterObjCustomerID["Predicate"] =
"0";
filterObjShipCountry["IsCaseSensitive"]=
filterObjCustomerID["IsCaseSensitive"]= false;
gridobj._search = [];
Array.add(gridobj._search, filterObjCustomerID);
Array.add(gridobj._search, filterObjShipCountry);
gridobj.sendRefreshRequest();
}</script>
[Controller]
searchConditionCollection)
{
List<FilterDescriptor> searchList = searchConditionCollection.ToList();
IEnumerable<FilterDescriptor> emptyConditions = searchList.Where(c =>
c.Value == null).ToList();
emptyConditions.ForEach(condition =>
{
searchList.Remove(condition);
});
IEnumerable<FilterDescriptor> blankConditions = searchList.Where(c =>
c.Value.ToString() == "(Blank)").ToList();
blankConditions.ForEach(condition =>
{
condition.Value = string.Empty;
});
Expression predicate = null;
Expression predicate2 = null;
IEnumerable<IGrouping<string,FilterDescriptor>>filtersgroups=searchList
.GroupBy(f => f.ColumnName);
[ASPX]
[Controller]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args, string searchdescriptors)
{
var engine = data.GridActions<Order>() as GridHtmlActionResult<Order>;
engine.GridModel.QueryCellInfo = onQueryCellAction;
return engine;
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args, string searchdescriptors)
{
object[] searchConditions = new JavaScriptSerializer().Deserialize<
object[]>(searchdescriptors);
IEnumerable data = new NorthwindDataContext().Orders.Take(200);
if (searchConditions != null && searchConditions.Count() > 0)
data=data.AsQueryable().Search(IQueryableHelper.ConvertObjToFilters(sea
rchConditions));
var engine = data.GridActions<Order>() as GridHtmlActionResult<Order>;
engine.GridModel.QueryCellInfo = onQueryCellAction;
return engine;
}
[Controller]
{
if (args.Column.MappingName == "OrderID")
{
args.Text = "<a href='http://www.google.com'>"+args.Data.OrderID +"</a>";
}
}
5.58 How to: Set the number of records per page and for
subsequent pages, by default.
You can follow these steps to set the number of records per page by default and in subsequent
pages.
1.Configure the grid with its properties.
View [cshtml]
@{Html.Syncfusion().Grid<EditableOrder>("OrderGrid")
.Column(cols =>
{
cols.Add(c => c.OrderID);
cols.Add(c => c.ShipCity);
cols.Add(c => c.ShipCountry);
cols.Add(c => c.Freight);
cols.Add(c => c.CustomerID);
})
.ClientSideEvents(events=>events.OnActionBegin("BeginAction"))
.EnablePaging()
.PageSettings(page => page.AllowPaging(true)
.PageSize(10)
.PagerStyle(PagerStyle.Default))
}
2. You can do this manually, by changing the PageSize according to the current page number in
“OnActionBegin” Client-Side events as shown in the following code example.
[JavaScript]
<script type="text/javascript">
function BeginAction(sender, args) {
var gridObj = $find('OrderGrid');
var pageNumber = parseInt(gridObj._pager._currentPageNo);
var clientobject =
Sys.Serialization.JavaScriptSerializer.deserialize(args.data.ClientObject);
switch (pageNumber) {
case 1:
clientobject["PageSize"] = 10;
break
case 2:
clientobject["PageSize"] = 5;
break;
case 3:
clientobject["PageSize"] = 25;
break;
case 4:
clientobject["PageSize"] = 100;
break;
}
args.data.ClientObject=Sys.Serialization.JavaScriptSerializer.serialize(clientobject);
}
</script>
View [cshtml]
@(Html.Syncfusion().Grid<JSONOrder>("UnBoundColumn_Grid")
.Datasource(Model)
.ActionMode(ActionMode.Server)
.Column(column =>
{
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.CustomerID).HeaderText("Customer ID");
column.Add(p => p.ShipCountry).HeaderText("Ship Country");
column.Add(p => p.ShipCity).HeaderText("ShipCity");
column.Add(p=>p.OrderDate).HeaderText("OrderDate").Format("{OrderDate:MM/dd/yyyy}");
column.Add("Image").HeaderText("Image").Format("<img src='" +
@Url.Content("~/Content/{EmployeeID}.png") + "'/>").UnBound(true);
}))
@{Html.Syncfusion().Grid<Order>("SampleGrid")
.Datasource(Model)
.Caption("Orders")
.Column(col =>
{
col.Add(c => c.OrderID);
col.Add(c => c.EmployeeID);
col.Add(c => c.CustomerID).HeaderText("CustID");
col.Add(c => c.Freight);
})
.ClientSideEvents(events =>
{
events.OnActionSuccess("complete");
})
.Editing(edit =>
{
edit.AllowEdit(true)
.AllowNew(true)
.AllowDelete(true);
edit.EditMode(GridEditMode.Dialog);
edit.PrimaryKey(key => key.Add(p => p.OrderID));
})
.Render();
}
[JavaScript]
<script type="text/javascript">
function complete(sender, args) {
var grid = $("#SampleGrid_EditDialog").find('#SampleGridFreight').keypress(
function (evt) { // SampleGrid is Grid ID and Freight is the column which is
need to bind keypress event.
alert('KeyPress event fired');
});
}
</script>
@{Html.Syncfusion().Grid<Order>("SampleGrid")
.Datasource(Model)
.Caption("Orders")
.Column(col =>
{
col.Add(c => c.OrderID);
col.Add(c => c.EmployeeID);
[JavaScript]
[Aspx]
@(Html.Syncfusion().Grid<EditableOrder>("SampleGrid")
.Datasource((IEnumerable<EditableOrder>)ViewData["data"])
.ActionMode(ActionMode.Server)
.Column(column =>
{
column.Add(c => c.OrderID).HeaderText("Order ID");
column.Add(c => c.OrderDate).HeaderText("Order Date");
column.Add(c => c.ShipCity).HeaderText("Ship City");
})
.ClientSideEvents(
evt => evt.OnActionBegin("Begin")
)
)
[JavaScript]
How to send the request to the Grid using External How to: Enum Dropdown in grid 1087
Button 824
How to: Format the cells through QueryCellInfo
How to Use Other Controls Inside the event 1045
DialogEditorTemplate? 1023
How to: Format the Grid columns 1035
How to: Get custom theme for multiple (Grid,
How to: Format the values in the filter dialog. 1054
Tools, Schedule) controlsHow to: Move Grid
rows Up and Down using Button 1047 How to: Get selected records in another view 1039
How to: Get properties of the grid 1039 How to: Get the selected row values in
ToolbarClick event 1029
How to: overcome “Check whether the grid post
action is defined in controller” error when How to: Hide columns when exporting Grid 1036
editing 1032
How to: Hide filter icon in grid table header 1049
How to: Refresh grid contents on external button
How to: Hide GroupHeaderArea when Grouping is
click 1028
defined in code 1063
How to: Resolve Database configuration error
How to: Hide MasterCellCollapse/Expand in
1027
Hierarchy Grid 1062
How to: Add a hyperlink to unbound Column of
How to: Import an Excel(.xlsx) file into Grid 1085
MVC Grid 1077
How to: Load only required rows from database,
How to: Add New, Delete and Update multiple
instead of loading all data. 1087
grids uing external button 1055
How to: Multiple Grid not showing on JQuery tabs
How to: Apply manual filtering to the grid with
1091
Queryparam 1081
How to: overcome “Registering style sheet for the
How to: Assign datasource for a DropdownEdit at
Grid failed because assembly does not exist”
clientside 1064
error 1026
How to: Avoid the duplicate row insertion and
How to: Preventing Grid focus at the top of grid
display error message 1083
1093
How to: Avoid validation messages invisibility
How to: Programmatically filter a column 1094
1028
How to: Remove up and down arrows in numeric
How to: Bind Javascript onkeypress event on
textbox 1078
editcell 1103
How to: Right align summary row values 1053
How to: Change dropdown to textbox cell for
particular cells when celledit type is dropdown How to: Save the Grid Content using an External
1060 Button. 1060
How to: Change entire column values in client How to: Set Grid height and width in Client-Side
side. 1068 1031
How to: Check which column is filtered in the How to: Set grouping initially with datatable
OnActionSuccess Client-Side event. 1074 elements 1080
How to: Click automation of the edit dialog save How to: Set Image Column using Url.Content 1102
button 1104
How to: Set the height of the grid rows 1050
How to: Custom server paging with initial grouping
How to: Set the number of records per page and
1051
for subsequent pages, by default. 1101
How to: Disable sorting for specific columns in
How to: Show tooltip on Grid Cell MouseHover in
Grid 1038
JSON mode 1043
RowDataBound Action 526 Through GridBuilder 40, 44, 49, 54, 58, 63, 71, 79,
87, 96, 106, 114, 117, 127, 136, 140, 144,
RowHeader 803
156, 163, 170, 177, 187, 202, 213, 224, 230,
RowHover 804 238, 247, 259, 301, 340, 352, 369, 384, 410,
425, 442, 469, 483, 489, 495, 500, 514, 521,
S
527, 532, 538, 551, 558, 565, 573, 579, 587,
sampleCustomize Methods 814 595, 602, 610, 613, 626, 637, 648, 653, 668,
678, 681, 688, 697, 710, 718, 726, 733, 747,
Samples and Location 25
774, 831, 841, 921, 959, 975
Save Request 829
Through GridProperties model 227, 415, 576
Scrolling 564, 1002
Through GridPropertiesModel 42, 46, 51, 56, 60,
Searching 230 66, 74, 83, 92, 101, 109, 115, 122, 131, 138,
142, 147, 160, 167, 172, 183, 192, 209, 218,
Searching Request 824
234, 243, 251, 282, 320, 345, 358, 375, 391,
Select and Deselect Methods 791 434, 451, 472, 484, 490, 497, 502, 518, 523,
530, 534, 542, 554, 561, 569, 581, 590, 597,
Selection 583
603, 611,615, 630, 643, 650, 660, 673, 713,
Selection functionality 812 723, 730, 736, 749, 779, 832, 844, 961, 977
Server Mode 40, 156, 177, 202, 237, 259, 425, Through MultiColumnDropDownModel 855, 866,
514, 527, 551, 678, 688, 718, 835, 896, 916 884, 899, 908, 918
Set Methods 786 Through MultiDropdownModel 861, 875, 879
Setting the Orientation 872 Toggle Selection 587
Settings for Essential Grid in MVC 4 Application Toolbar 840
930
ToolbarOptions Table 846
Show and Hide Methods 796
U
Sorting 176, 819, 896, 995
Unbound Column 62
Sorting customization 181, 185, 190, 195
Unbound Column Editing 421
Sorting Methods 819
Unbound Column Support 1006
Sorting Request 826
Unfreezing Panes 741
Stacked Headers 706
Ungroup Column 822
Strongly Typed View 932
Using CssClass() 509
Summaries 545, 1001
Using Format() 506
Syncfusion Utilites 29
V
T
Virtual Scrolling in MVC Grid 572
Tables for Properties, Methods, and Events 364,
Virtual Scrolling Mode 573
525, 537, 616, 716
W
Through Builder 854, 860, 864, 873, 877, 882,
896, 902, 916 Web Service Data Binding 127
Through Grid Client Object 780 Word Export 486
Word Export Request 827