Custom Exporting

  • 5 minutes to read
TIP

Starting with version 17.2, we recommend using the client API, built-in toolbar and context menu commands for ASPxGridView data exporting.

The ASP.NET MVC GridView extension allows exporting the MVCxGridView records to CSV, PDF, RTF, XLS and XLSX format using the methods listed in the Member Table: Custom Export topic.

Declare the master grid settings (a GridViewSettings type object) and an object the grid is bound to. We recommended declaring grid settings in the Controller code (or any other helper code) and passing them to the View code to avoid repeatedly declaring and initializing grid settings. In the example below, the grid settings are declared within the Controller code and can be retrieved using static methods.

Example

The code sample below demonstrates how to implement the MVCxGridView data exporting.

Controller code:

using System.Linq;
using System.Web.Mvc;
using DevExpress.Web.Mvc;

namespace MyProject.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewBag.GridSettings = GetGridSettings();
            return View();
        }
        // The Entity Framework data context
        MyProject.Models.northwndEntities db = new MyProject.Models.northwndEntities();

        // Handles GridView callbacks.
        [ValidateInput(false)]
        public ActionResult GridViewPartial()
        {
            ViewBag.GridSettings = GetGridSettings();
            var model = db.Products;
            return PartialView("_GridViewPartial", model.ToList());
        }

        // This action method sends a PDF document with the exported Grid to response.
        public ActionResult ExportTo()
        {
            var model = db.Products;
            return GridViewExtension.ExportToPdf(GetGridSettings(), model.ToList());
        }

        // Returns the settings of the exported GridView.
        private GridViewSettings GetGridSettings() {
            var settings = new GridViewSettings();
            settings.Name = "GridView";
            settings.CallbackRouteValues = new { Controller = "Home", Action = "GridViewPartial" };

            // Export-specific settings 
            settings.SettingsExport.ExportSelectedRowsOnly = false;
            settings.SettingsExport.FileName = "Report.pdf";
            settings.SettingsExport.PaperKind = System.Drawing.Printing.PaperKind.A4;

            settings.KeyFieldName = "ProductID";
            settings.Columns.Add("ProductName");
            settings.Columns.Add("UnitPrice").PropertiesEdit.DisplayFormatString = "c";
            settings.Columns.Add("QuantityPerUnit");
            settings.Columns.Add("Discontinued", MVCxGridViewColumnType.CheckBox);

            return settings;
        }
    }
}

View code("Index"):

@Html.Action("GridViewPartial")

// When an end-user clicks this button, the button sends a callback to the "ExportTo" action and  
// the server sends the resulting export file to the response.
@Html.DevExpress().Button(settings =>
{
    settings.Name = "Button";
    settings.UseSubmitBehavior = false;
    settings.Text = "ExportTo PDF";
    settings.RouteValues = new { Controller = "Home", Action = "ExportTo" };
}).GetHtml()

Partial View code ("_GridViewPartial"):

@{
    var grid = Html.DevExpress().GridView(ViewBag.GridSettings);
}
@grid.Bind(Model).GetHtml()

Master-Detail

To export the grid's master-detail records, the master grid settings should contain export-specific settings and a delegate method assigned to the MVCxGridViewExportSettings.GetExportDetailGridViews property. Using this delegate method adds a bound to data detail grid to the GridViewExportDetailRowEventArgs.DetailGridViews collection (see the GetMasterGridSettings action method within the Controller code in the example below).

Example

The code sample below demonstrates how to export the grid's master-detail records.

Controller code ("HomeController"):

using DevExpress.Web.ASPxGridView;
using DevExpress.Web.Mvc;
using System.Linq;
using System.Web.Mvc;
using System.Web.UI;

namespace MasterDetailExportDemo.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        // Entity Framework data context
        MasterDetailExportDemo.Models.northwndEntities db = new MasterDetailExportDemo.Models.northwndEntities();

        // This action method sends a PDF document with the exported Grid to response.
        public ActionResult ExportTo()
        {
            var model = db.Categories;
            return GridViewExtension.ExportToPdf(GetMasterGridSettings(), model.ToList());
        }

        // Returns the settings of the detail GridView.
        public static GridViewSettings GetDetailGridSettings(int uniqueKey)
        {
            var settings = new GridViewSettings();
            // Each extension rendered to the View must have a unique Name.
            settings.Name = "DetailGridView_" + uniqueKey;
            settings.KeyFieldName = "ProductID";
            settings.Columns.Add("ProductName");
            settings.Columns.Add("UnitPrice").PropertiesEdit.DisplayFormatString = "c";
            settings.Columns.Add("QuantityPerUnit");
            settings.Columns.Add("Discontinued", MVCxGridViewColumnType.CheckBox).Name = "Discontinued";
            settings.SettingsDetail.MasterGridName = "GridViewMaster";
            return settings;
        }

        // Returns the settings of the master GridView.
        public static GridViewSettings GetMasterGridSettings()
        {
            var settings = new GridViewSettings();
            settings.Name = "GridViewMaster";
            settings.KeyFieldName = "CategoryID";
            settings.Columns.Add("CategoryName");
            settings.Columns.Add("Description");

            // Export-specific settings
            settings.SettingsExport.ExportedRowType = DevExpress.Web.Export.GridViewExportedRowType.All;
            settings.SettingsExport.FileName = "Report.pdf";
            settings.SettingsExport.PaperKind = System.Drawing.Printing.PaperKind.A4;
            settings.SettingsDetail.ShowDetailRow = true;
            settings.SettingsDetail.ExportMode = GridViewDetailExportMode.All;
            // This code retrieves data for the detail grid when performing the export.
            // To retrieve the records for the detail grid when displaying the grid to end-users,
            // refer to the "GridViewDetailPartial" action method.
            settings.SettingsExport.GetExportDetailGridViews = (s, e) =>
            {
                int categoryID = (int)DataBinder.Eval(e.DataItem, "CategoryID");
                GridViewExtension grid = new GridViewExtension(GetDetailGridSettings(categoryID));
                var products = new MasterDetailExportDemo.Models.northwndEntities().Products;
                var model = from product in products where product.CategoryID == categoryID select product;
                grid.Bind(model.ToList());
                e.DetailGridViews.Add(grid);
            };
            return settings;
        }

        // Handles master GridView callbacks.
        [ValidateInput(false)]
        public ActionResult GridViewMasterPartial()
        {
            var model = db.Categories;
            return PartialView("_GridViewMasterPartial", model.ToList());
        }

        // Handles detail GridView callbacks.
        [ValidateInput(false)]
        public ActionResult GridViewDetailPartial(int categoryID)
        {
            ViewBag.CategoryID = categoryID;
            var products = db.Products;
            // Detail grid is bound to a list of products of a certain category.
            var model = from product in products where product.CategoryID == categoryID select product;
            return PartialView("_GridViewDetailPartial", model.ToList());
        }
    }
}

View code ("Index"):

@{
    Html.RenderAction("GridViewMasterPartial");

    // When an end-user clicks this button, the button send a callback to the "ExportTo" action and 
    // the server sends the resulting export file to the response. 
    Html.DevExpress().Button(settings =>
    {
        settings.Name = "Button";
        settings.UseSubmitBehavior = false;
        settings.Text = "Export To PDF";
        settings.RouteValues = new { Controller = "Home", Action = "ExportTo" };
    }).Render();
}

Partial View (Master Grid):

@{
    GridViewSettings settings = MasterDetailExportDemo.Controllers.HomeController.GetMasterGridSettings();
    settings.CallbackRouteValues = new { Controller = "Home", Action = "GridViewMasterPartial" };
    // Renders the detail GridView within the detail row.
    settings.SetDetailRowTemplateContent(c =>
    {
        Html.RenderAction("GridViewDetailPartial", new { CategoryID = DataBinder.Eval(c.DataItem, "CategoryID") });
    });
}
@Html.DevExpress().GridView(settings).Bind(Model).GetHtml()

Partial View (Detail Grid):

@{
    var settings = MasterDetailExportDemo.Controllers.HomeController.GetDetailGridSettings(ViewBag.CategoryID);
    settings.CallbackRouteValues = new { Controller = "Home", Action = "GridViewDetailPartial", CategoryID = ViewBag.CategoryID };
}
@Html.DevExpress().GridView(settings).Bind(Model).GetHtml()
See Also