Displaying DataTables in Asp.Net MVC Razor Page

In this tutorial, we'll learn how to display a DataTable in an Asp.Net MVC razor.

Step 1: Set Up Your MVC Project

  1. Open Visual Studio: Launch Visual Studio, and create a new ASP.NET MVC project.

  2. Create a Controller: Right-click on the "Controllers" folder, select "Add," then "Controller." Choose "MVC 5 Controller - Empty" and name it as you wish.

  3. Create an Action Method: Inside your controller, create an action method that will return the DataTable to your view.

    using System.Data;
    using System.Web.Mvc;
    
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            DataTable dataTable = GetDataTableFromSource();
            return View(dataTable);
        }
    
        private DataTable GetDataTableFromSource()
        {
            DataTable dataTable = new DataTable();
            dataTable.Columns.Add("ID", typeof(int));
            dataTable.Columns.Add("Name", typeof(string));
    
            dataTable.Rows.Add(1, "John");
            dataTable.Rows.Add(2, "Alice");
            dataTable.Rows.Add(3, "Bob");
    
            return dataTable;
        }
    }
    

Step 2: Create a View

  1. Add a View: Right-click on the "Views" folder within your controller's folder, select "Add," then "View." Name the view as your action method (e.g., "Index").

  2. Use the DataTable in the View: In your view file (e.g., "Index.cshtml"), use the following code to display the DataTable.

    @using System.Data
    
    <table id="myTable">
        <thead>
            <!-- Render table headers -->
            <tr>
                @foreach (DataColumn column in Model.Columns)
                {
                    <th>@column.ColumnName</th>
                }
            </tr>
        </thead>
        <tbody>
            <!-- Render table rows -->
            @foreach (DataRow row in Model.Rows)
            {
                <tr>
                    @foreach (var cell in row.ItemArray)
                    {
                        <td>@cell</td>
                    }
                </tr>
            }
        </tbody>
    </table>
    

Step 3: Run Your Application

  1. Build Your Project: Click on the "Build" menu and select "Build Solution" to compile your project.

  2. Run Your Application: Press F5 or click on the "Start" button to run your application.

  3. View the DataTable: Navigate to the URL of your application, and you should see the DataTable displayed in your view.

 
About Us | Terms of Use | Privacy Policy | Disclaimer | Contact Us Copyright © 2012-2024 CodingFusion
50+ C# Programs for beginners to practice