Lesson 2 - Use the Resulting Query
- 3 minutes to read
This lesson demonstrates how to use queries that the Query Builder generates to supply data to the DevExpress ASP.NET MVC GridView control.
Pass the Query Data to the GridView
Create a new Partial View file (for instance, GridViewPartial.cshtml), since the GridView updating mechanism requires declaring its extension in the Partial View. Use the ExtensionsFactory.GridView helper method and pass the GridViewSettings object as a parameter to configure the extension as shown below:
@Html.DevExpress().GridView(settings => { settings.Name = "grid"; settings.Width = Unit.Percentage(100); settings.CallbackRouteValues = new { Controller = "Home", Action = "GridViewPartial" }; settings.SettingsBehavior.AllowEllipsisInText = true; }).Bind(Model).GetHtml()
- Move the Query Builder extension’s declaration from the Index.cshtml file to a new separate View file (QueryBuilder.cshtml in this example).
In the Index.cshtml file, render the GridView and provide the capability to run the Query Builder using the following code:
@model SqlDataSource <a href="@Url.Action("QueryBuilder")">Run Query Builder</a> <p /><p /> @Html.Partial("GridViewPartial", Model)
In the Query Builder controller, modify the Save action to save the QueryBuilderSaveCallbackResult.SelectStatement property value to the session variable and redirect a browser to the page with the GridView.
using DevExpress.Web.Mvc; public class QueryBuilderController : DevExpress.Web.Mvc.Controllers.QueryBuilderApiController { // ... public ActionResult Save() { var result = QueryBuilderExtension.GetSaveCallbackResult("QueryBuilder"); Session["SelectCommand"] = result.SelectStatement; return RedirectToAction("Index", "Home"); } }
Open the HomeController file and implement the action methods as demonstrated below:
using System.Web.Mvc; using System.Configuration; public class HomeController : Controller { string NorthwindConnectionString { get { return ConfigurationManager.ConnectionStrings["NorthwindConnection"].ConnectionString; } } System.Web.UI.WebControls.SqlDataSource DataSource { get { var select = @"select [Suppliers].[CompanyName] from [dbo].[Suppliers]"; // The default SELECT statement. if (Session["SelectCommand"] != null) { select = Session["SelectCommand"] as string; } return new System.Web.UI.WebControls.SqlDataSource(NorthwindConnectionString, select); } } public ActionResult Index() { return View(DataSource); } public ActionResult QueryBuilder() { return View("QueryBuilder"); } public ActionResult GridViewPartial() { return PartialView(DataSource); } }
View the Result
Run the application to see the GridView displaying the default data and click the Run Query Builder link.
In the invoked Query Builder, construct a query and click the Save toolbar button.
This opens the page with the GridView that shows the obtained data.