Asp net core 7 mvc sending database data to view


ASP.NET is a popular programming language used for building web applications. In this article, we will explore how to send database data to a view in ASP.NET Core 7 MVC.

Setting up the Database

we can send database data to a view, we need to set up a database and establish a connection to it. Let's assume we have a SQL Server database named “MyDatabase” with a table named “Customers”.

// Database connection string
string  = "Server=localhost;Database=MyDatabase;Trusted_Connection=True;";

// Create a new SqlConnection object
using (SqlConnection connection = new SqlConnection(connectionString))
    // Open the connection

    // Perform database operations
    // ...

Retrieving Data from the Database

Once we have established a connection to the database, we can retrieve data from the “Customers” table. We will use a SqlCommand object to execute a SQL query and retrieve the data.

// SQL query to retrieve data from the Customers table
string query = " * FROM Customers";

// Create a new SqlCommand object
using (SqlCommand  = new SqlCommand(query, connection))
    // Execute the query and retrieve the data
    SqlDataReader reader = command.ExecuteReader();

    // Process the retrieved data
    while (reader.Read())
        // Access the data using the reader object
        string customerId = reader["CustomerId"].ToString();
        string customerName = reader["CustomerName"].ToString();

        // Do something with the data
        // ...

    // Close the reader

Sending Data to the View

Now that we have retrieved the data from the database, we can send it to the view. In ASP.NET Core MVC, we can use a to pass data from the controller to the view.

, let's create a model class to represent the data we retrieved from the database:

    public string CustomerId { get; set; }
    public string CustomerName { get; set; }

Next, in the controller action method, we can populate a list of Customer objects with the retrieved data and pass it to the view:

public IActionResult Index()
    List customers = new List();

    // Retrieve data from the database and populate the customers list
    // ...


Finally, in the view, we can access the data using the model:

@model List

@foreach (var customer in Model)

Customer ID: @customer.CustomerId

Customer Name: @customer.CustomerName



In this article, we have learned how to send database data to a view in ASP.NET Core 7 MVC. By establishing a connection to the database, retrieving the data, and it to the view using a model, we can display the database data in our web application.

Rate this post

Leave a Reply

Your email address will not be published. Required fields are marked *

Table of Contents