Friday, 12 April 2024 08:45

how to get data from a database and display across multiple pages in ASP.NET MVC

Written by 
Rate this item
(0 votes)

To display data from a database in an ASP.NET MVC application across multiple pages, you can follow these general steps:

Create a Model: Define a model class that represents the data you want to display.

  1. Set up a Database Context: Create a database context class that inherits from DbContext (if using Entity Framework) or any other data access mechanism of your choice.

  2. Retrieve Data from the Database: Write a method in your data access layer to retrieve the data from the database.

  3. Pass Data to Views: Pass the retrieved data to the views where you want to display it.

  4. Display Data in Layout or Partial View: Display the data in the layout or a partial view that is included in all pages where you want to display the list.

Here's a simplified example to illustrate these steps:

Assuming you have a model class called Item:

public class Item { public int Id { get; set; } public string Name { get; set; } // Other properties }
  1. Create a Database Context:
public class YourDbContext : DbContext { public DbSet<Item> Items { get; set; } // Other DbSet properties }
  1. Retrieve Data from the Database:
public class YourRepository { private readonly YourDbContext _dbContext; public YourRepository(YourDbContext dbContext) { _dbContext = dbContext; } public List<Item> GetAllItems() { return _dbContext.Items.ToList(); } }
  1. Pass Data to Views:

In your controller action method:

public class YourController : Controller { private readonly YourRepository _repository; public YourController(YourRepository repository) { _repository = repository; } public IActionResult YourAction() { var items = _repository.GetAllItems(); return View(items); } }
  1. Display Data in Layout or Partial View:

Create a partial view _ItemList.cshtml:

@model List<Item> <ul> @foreach (var item in Model) { <li>@item.Name</li> } </ul>

Include this partial view in your layout or other views:

@Html.Partial("_ItemList", Model)

This will display the list of items in the layout or view wherever you include this partial view. Ensure you pass the required model to the view containing this partial view.

Read 132 times Last modified on Friday, 12 April 2024 08:55
Super User

Email This email address is being protected from spambots. You need JavaScript enabled to view it.

Latest discussions

  • No posts to display.