Donate

Getting Started With Bootstrap-Table In An ASP.NET Core MVC 5 Web Application With Entity Framework Core And SQL Server

Hello,

In this tutorial, I will demonstrate on how to integrate Bootstrap-Table created by Wenzhixin in an ASP.NET Core MVC 5 with Entity Framework Core and SQL Server. For this post, I'll be using Microsoft's free database called ContosoRetailDW. Most of the ASP.NET MVC 5 web project in our company use this widget for showing records to clients because this has tons of features like exporting, paging, searching, sorting by column names and a whole lot more and this awesome widget has been constantly improved by the product owner and some dedicated developers.

Project Setup

1. Lets start by creating an ASP.NET Core MVC application targeting the latest framework which is .NET 5 using Visual Studio 2019.
2. Add these NuGet packages for Entity Framework Core and ASP.NET Core MVC Newtonsoft.Json
Getting Started With Bootstrap-Table In An ASP.NET Core MVC 5 Web Application With EF Core And SQL Server
3. Next is to reverse engineer the ContosoRetailDW so that we can use it's tables. The bootstrap-table widget will load records from DimPromotions table.
Scaffold-DbContext "Server=Your_Server;Database=ContosoRetailDW;Integrated Security=True" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models
4. Add via libman bootstrap-table and font-awesome libraries.
Getting Started With Bootstrap-Table In An ASP.NET Core MVC 5 Web Application With EF Core And SQL Server
5. Download the latest tableExport.js (1.20.0) from github and copy that file inside the bootstrap-table folder of your project.
Getting Started With Bootstrap-Table In An ASP.NET Core MVC 5 Web Application With EF Core And SQL Server

Coding The Controller and Startup Files

1. In your Startup.cs file, we need to add JSON options to MVC since this is useful in displaying JSON data. Without setting this option, your table will display empty cells instead of the actual records.
 public void ConfigureServices(IServiceCollection services)
      {
         services.AddControllersWithViews();
         services.AddMvc().AddJsonOptions(options => {
            options.JsonSerializerOptions.PropertyNameCaseInsensitive = false;
            options.JsonSerializerOptions.PropertyNamingPolicy = null;
         });
      }
2. HomeController.cs - This class has a method that will retrieve all promotions data from ContosoRetailDW and returns the results as a JSON object. The ContosoRetailDWContext object is responsible for getting the information from the database.
public class HomeController : Controller
   {
      private readonly ILogger<HomeController> _logger; 
      private ContosoRetailDWContext _context;

      public HomeController(ILogger<HomeController> logger)
      {
         _logger = logger;
         _context = new ContosoRetailDWContext();
      }

      public IActionResult Index()
      {
         return View();
      }

      [HttpGet]
      public JsonResult GetPromotionData()
      {
         var data = _context.DimPromotions.ToList();

         return Json(data);
      }
   }

Coding The Views

1. Layout.cshtml - In your Layout page, reference the font-awesome library it's because the recent Bootstrap-Table will utilize these icons.
<head>
   <meta charset="utf-8" />
   <meta name="viewport" content="width=device-width, initial-scale=1.0" />
   <title>@ViewData["Title"] - ASP.Net Core MVC Bootstrap-Table Example</title>
   <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
   <link rel="stylesheet" href="~/css/site.css" />
   <link href="~/lib/font-awesome/css/all.css" rel="stylesheet" />
</head>
2. Index.cshtml - This view is responsible for showing the promotions information from ContosoRetailsDW using the Bootstrap-Table widget. In our scripts section, we need to reference the CSS and JavaScript files of the widget depending on the features that you need. We must also initialize our Bootstrap-Table toolbar in the document.ready function so that we can export the page or all of the information with different types of format. Next is to set the table options columns especially the data-url that calls the controller method that returns the JSON data and identify the properties that needs to be shown to the table. For this demo, I only include nine columns to be displayed to the user.
@{
   ViewData["Title"] = "Home Page";
}

<div id="divPageContainer">
   <div id="toolbar">
      <select class="form-control">
         <option value="">Export Page</option>
         <option value="all">Export All</option>
      </select>
   </div>
   <div id="divPromotion" class="table-responsive">
      <table id="tblPromotion"
             class="table-condensed table-striped"
             data-toggle="table"
             data-search="true"
             data-sort-name="PromotionKey"
             data-sort-order="asc"
             data-show-columns="true"
             data-advanced-search="true"
             data-id-table="advancedTable"
             data-show-multi-sort="true"
             data-show-export="true"
             data-toolbar="#toolbar"
             data-click-to-select="true"
             data-cookie="true"
             data-pagination="true"
             data-show-jump-to="true"
             data-url='@Url.Action("GetPromotionData", "Home")'
             data-cookie-id-table="tblPromotionID"
             data-page-size="10"
             data-page-list="[10, 25, 500, 1000, 10000, All]">
         <thead>
            <tr style="background-color: #FFFFFF;">
               <th data-field="PromotionKey" data-visible="true" data-searchable="true">Promotion Key</th>
               <th data-field="PromotionLabel" data-sortable="true" data-searchable="true">Promotion Label</th>
               <th data-field="PromotionName" data-sortable="true" data-searchable="true">Promotion Name</th>
               <th data-field="PromotionDescription" data-sortable="true" data-searchable="true">Description</th>
               <th data-field="DiscountPercent" data-sortable="true" data-searchable="true">Discount Percent</th>
               <th data-field="PromotionType" data-sortable="true" data-searchable="true">Promotion Type</th>
               <th data-field="PromotionCategory" data-sortable="true" data-searchable="true">Promotion Category</th>
               <th data-field="StartDate" data-sortable="true" data-searchable="true">Start Date</th>
               <th data-field="EndDate" data-sortable="true" data-searchable="true">End Date</th>
            </tr>
         </thead>
      </table>
   </div>
</div>

@section scripts{
   <link href="~/lib/bootstrap/dist/css/bootstrap.css" rel="stylesheet" />
   <link href="~/lib/bootstrap-table/bootstrap-table.min.css" rel="stylesheet" />
   <link href="~/lib/bootstrap-table/extensions/page-jump-to/bootstrap-table-page-jump-to.css" rel="stylesheet" />
   <link href="~/lib/bootstrap-table/extensions/filter-control/bootstrap-table-filter-control.css" rel="stylesheet" />
   <script src="~/lib/bootstrap-table/bootstrap-table.js" type="module"></script>
   <script src="~/lib/bootstrap-table/extensions/toolbar/bootstrap-table-toolbar.js" type="module"></script>
   <script src="~/lib/bootstrap-table/extensions/multiple-sort/bootstrap-table-multiple-sort.js" type="module"></script>
   <script src="~/lib/bootstrap-table/extensions/export/bootstrap-table-export.js" type="module"></script>
   <script src="~/lib/bootstrap-table/extensions/cookie/bootstrap-table-cookie.js" type="module"></script>
   <script src="~/lib/bootstrap-table/extensions/page-jump-to/bootstrap-table-page-jump-to.js" type="module"></script>
   <script src="~/lib/bootstrap-table/tableExport.js"></script>
   <style type="text/css">
      #divPromotion {
         margin-bottom: 150px;
      }

      #divPageContainer {
         width: 80%;
         margin: auto;
      }
   </style>
   <script type="text/javascript">

      $(function () {
         ToolbarInit();
      });

      function ToolbarInit() {
         $('#toolbar').find('select').change(function () {
            $('#tblPromotion').bootstrapTable('destroy').bootstrapTable({
               exportDataType: $(this).val(),
               exportTypes: ['json', 'xml', 'csv', 'txt', 'sql', 'excel']
            })
         }).trigger('change');
      }
   </script>
}
When running the application without errors, the Index page will render the Bootstrap-Table with the records from the database. You can then perform page navigation, sort and search columns and exporting of records.
Getting Started With Bootstrap-Table In An ASP.NET Core MVC 5 Web Application With Entity Framework Core And SQL Server

Cheers!

Comments

Donate

Popular Posts From This Blog

WPF CRUD Application Using DataGrid, MVVM Pattern, Entity Framework, And C#.NET

How To Insert Or Add Emojis In Microsoft Teams Status Message

Bootstrap Modal In ASP.NET MVC With CRUD Operations