Search code examples
javascriptc#htmlasp.net-core

Load Data from Database to the HTML Table in ASP.Net Core MVC


I am working on an ASP.NET Core MVC C# project and need assistance with loading data from a database into an HTML table dynamically. Suppose that I have a controller and razor cshtml file. The below shown code is in the cshtml file. And how I can implement the controller for loading data from database and load the data into this table ???

        <style>
          table {
            margin: 0 auto;
            margin-top: 20px;
            width: 100%;
            position: relative;
            overflow: auto;
            overflow-y: overlay;
         }

        th, thead {
          position: sticky;
          top: 0;
          border: 1px solid #dddddd;
          background-color: #1f2d54;
          text-align: center;
          color: white;
          table-layout: fixed;
          word-break: break-word;
          height: 45px;
        }          
       </style>

       <table style='padding: 8px;'>
       <thead>
        <tr>
             <th index=0>Email<div class="filter"></div></th>
             <th index=1>Name<div class="filter"></div></th>
             <th index=2>Level<div class="filter"></div></th>
             <th index=3>Location<div class="filter"></div></th>
        </tr>
         </thead>
         <tbody>
    
         </tbody>
       </table>

Solution

  • you can do it follow the official tutorial:

    https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app/adding-model?view=aspnetcore-8.0&tabs=visual-studio

    Here's an example:

    1). create a model named Users.cs

    public class Users
    {
        public int Id { get; set; }
        public string Email { get; set; }
        public string Name { get; set; }
        public string Level { get; set; }
        public string Location { get; set; }
    }
    

    2). Use the scaffolding tool to produce Create, Read, Update, and Delete (CRUD) pages for the Users model

    3). Use the EF Core Migrations feature to create the database. Migrations is a set of tools that create and update a database to match the data model.

    The result is as follows:

    enter image description here