Articles in this section
Category / Section

How to pass additional parameter to server in ASP.NET MVC Grid?

1 min read

How to pass additional parameter to server while exporting

The Export feature in Grid will allow the user to export the grid content to Excel, PDF or Word file formats. And the Grid model will be posted to the server on export operation.

If we want to send any additional parameter to the server then we can do this by adding the additional parameter to the grid model and retrieving it at the server side.

Let us discuss how to send a numeric textbox value along with grid model and retrieve it at the server while exporting.

Grid Initialization

JS

 
<input type="text" id="count" />
 
<div id="Grid"></div>
 
<script type="text/javascript">
 
$(function () {
                $("#count").ejNumericTextbox({
                    maxValue: 10
                })
 
                $("#Grid").ejGrid({
                    dataSource: window.gridData,
                    allowPaging: true,
                    toolbarSettings: { showToolbar: true, toolbarItems: [ej.Grid.ToolBarItems.ExcelExport, ej.Grid.ToolBarItems.WordExport, ej.Grid.ToolBarItems.PdfExport] },
                    columns: [
                         { field: "OrderID", headerText: "Order ID", textAlign: ej.TextAlign.Right, width: 70 },
                         { field: "EmployeeID", width: 70, textAlign: ej.TextAlign.Right, headerText: "Employee ID" },
                         { field: "CustomerID", width: 70, headerText: "Customer ID" },
                         { field: "Freight", headerText: "Freight", textAlign: ej.TextAlign.Right, width: 70, format: "{0:C2}" }
                    ],
                    toolbarClick: function (args) {
 
                        if (args.itemName.indexOf("Export") > -1) { //Add the extra paramater to send to server
                            this.model["recordCount"] = $("#count").ejNumericTextbox("model.value");
                        }
 
                        if (args.itemName == "Excel Export") {
                            args.cancel = true;
                            this.export("api/Grid/ExcelExport"); // Excel Export method.
                        }
                        if (args.itemName == "Word Export") {
                            args.cancel = true;
                            this.export("api/Grid/WordExport"); // Word Export method.
                        }
                        if (args.itemName == "PDF Export") {
                            args.cancel = true;
                            this.export("api/Grid/PdfExport"); // PDF Export method.
                        }
                    }
                });
            });
 
</script>
 

 

MVC

 
@(Html.EJ().NumericTextbox("count").MaxValue(10))
 
@(Html.EJ().Grid<object>("Grid")
      .Datasource((IEnumerable<Orders>)ViewBag.datasource)
      .ToolbarSettings(tool => tool.ShowToolbar().ToolbarItems(item =>
       {
        item.AddTool(ToolBarItems.ExcelExport);
        item.AddTool(ToolBarItems.PdfExport);
        item.AddTool(ToolBarItems.WordExport);
       }))
      .Columns(col =>
        {
            col.Field("OrderID").HeaderText("Order ID").TextAlign(TextAlign.Right).Width(70).Add();
            col.Field("CustomerID").HeaderText("Customer ID").Width(70).Add();
            col.Field("EmployeeID").HeaderText("Employee ID").TextAlign(TextAlign.Right).Width(70).Add();
            col.Field("Freight").HeaderText("Freight").Format("{0:C2}").TextAlign(TextAlign.Right).Width(70).Add();
        })
      .Mappers(map => map.ExportToExcelAction(@Url.Action("ExcelExport"))
                         .ExportToPdfAction(@Url.Action("PdfExport"))
                         .ExportToWordAction(@Url.Action("WordExport")))
      .ClientSideEvents(evt => evt.ToolbarClick("OnToolbarClick"))
    )
 

 

ASP

 
<ej:Grid runat="server" ID="Grid" AllowPaging="true" OnServerExcelExporting="Grid_ExcelExporting" OnServerWordExporting="Grid_WordExporting" OnServerPdfExporting="Grid_PDFExporting">
        <Columns>
            <ej:Column Field="OrderID" HeaderText="Order ID" Width="70" TextAlign="Right"></ej:Column>
            <ej:Column Field="CustomerID" HeaderText="Customer ID" Width="70"></ej:Column>
            <ej:Column Field="EmployeeID" HeaderText="Employee ID" Width="70" TextAlign="Right"></ej:Column>
            <ej:Column Field="Freight" HeaderText="Freight" Width="70" Format="{0:C2}" TextAlign="Right"></ej:Column>
        </Columns>
        <ToolbarSettings ShowToolbar="true" ToolbarItems="excelExport,wordExport,pdfExport"></ToolbarSettings>    
        <ClientSideEvents ToolbarClick="OnToolbarClick" />   
    </ej:Grid>
 

 

The toolbar click handler for the MVC and ASP initialized Grid is as follows.

 
function OnToolbarClick(args) {
        if (args.itemName.indexOf("Export") > -1) {
            this.model["recordCount"] = $("#count").ejNumericTextbox("model.value");
        }
    }

 

Controller

 
  public class GridController : ApiController
    {
 
        public IEnumerable<Order> order = new NorthwindDataContext().OrdersViews.ToList()
 
        public int RecordCount { get; set; }
 
        [System.Web.Http.ActionName("ExcelExport")]
        [AcceptVerbs("POST")]
        public void ExcelExport()
        {
 
            string gridModel = HttpContext.Current.Request.Params["GridModel"];
 
            GridProperties gridPropert = ConvertGridObject(gridModel);
 
            ExcelExport exp = new ExcelExport();
 
            IEnumerable data = order.Take(RecordCount);
 
            exp.Export(gridPropert, (IEnumerable)data, "Export.xlsx", ExcelVersion.Excel2010, false, false, "flat-azure-dark");
 
 
        }
 
        [System.Web.Http.ActionName("WordExport")]
 
        [AcceptVerbs("POST")]
 
        public void WordExport()
        {
            string gridModel = HttpContext.Current.Request.Params["GridModel"];
 
            GridProperties gridPropert = ConvertGridObject(gridModel);
 
            WordExport exp = new WordExport();
 
            IEnumerable data = order.Take(RecordCount);;
 
            exp.Export(gridPropert, (IEnumerable)data, "Export.docx");
 
 
        }
 
        [System.Web.Http.ActionName("PdfExport")]
 
        [AcceptVerbs("POST")]
 
        public void PdfExport()
        {
            string gridModel = HttpContext.Current.Request.Params["GridModel"];
 
            GridProperties gridPropert = ConvertGridObject(gridModel);
 
            PdfExport exp = new PdfExport();
 
            IEnumerable data = order.Take(RecordCount);
 
            exp.Export(gridPropert, (IEnumerable)data, "Export.pdf");
 
        }
 
        private GridProperties ConvertGridObject(string gridProperty)
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            IEnumerable div = (IEnumerable)serializer.Deserialize(gridProperty, typeof(IEnumerable));
            GridProperties gridProp = new GridProperties();
            foreach (KeyValuePair<string, object> ds in div)
            {
                var property = gridProp.GetType().GetProperty(ds.Key, BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase);
 
                //Check and retrieve additional property here
                if (ds.Key == "recordCount")
                {
                    RecordCount = (int)ds.Value;
                    continue;
                }
 
                if (property != null)
                {
                    Type type = property.PropertyType;
                    string serialize = serializer.Serialize(ds.Value);
                    object value = serializer.Deserialize(serialize, type);
                    property.SetValue(gridProp, value, null);
                }
            }
            return gridProp;
        }
 
 
    }
 

 

We have used the Web API controller to perform the export operation and we can also MVC controllers or ASP.Net web methods to perform export.

The following is the output generated from the above code example.

Figure 1: Grid with export enable and numeric textbox

Figure 2: Retrieving the additional parameter at the server side.

Figure 3: Exported Excel document.

Conclusion

I hope you enjoyed learning about how to pass additional parameter to server while exporting in ASP.NET MVC Grid. You can refer to our ASP.NET MVC Grid feature tour page to know about its other groundbreaking feature representations documentation and how to quickly get started for configuration specifications.  You can also explore our ASP.NET MVC Grid example to understand how to create and manipulate data.

For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our other controls.

If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forumsDirect-Trac, or feedback portal. We are always happy to assist you!

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please sign in to leave a comment
Access denied
Access denied