In this article i will show you how you can display data in table r tabular format in asp.net core 6 or mvc using c#.net using ms sql database. Here are the links of my previous articles Asp.Net Core 6: Connect To Sql Server Database With Entity Framework Using C#, Access Connection String In Asp.Net Core 6 Controller From appsettings.json C#, appsettings.json Connection String Value Access in Asp.net Core Controller, How To Change Default Page Or View In Asp.Net Core 6.
First we will a sql table and add some data on it. Here i have created an employee table and added some record.
So for this article we will create a new asp.net core mvc application and write the code to access the above employee table and display it on screen. Now will make connection with data base using entity framework in c#.net.
In this article i will only explain how to get data from data base and display the data on screen in your asp.net core 6/mvc application. To know how to make connection with sql database "Asp.Net Core 6: Connect To Sql Server Database With Entity Framework Using C#".
Ones you done with connection just check your db context file for connection string.
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { if (!optionsBuilder.IsConfigured) { #warning To protect potentially sensitive information in your connection
string, you should move it out of source code. You can avoid scaffolding the
connection string by using the Name= syntax to read it from configuration -
see https://go.microsoft.com/fwlink/?linkid=2131148. For more guidance on
storing connection strings, see http://go.microsoft.com/fwlink/?LinkId=723263. optionsBuilder.UseSqlServer("Server=..\\SQLEXPRESS;Database=TestDB;Trusted_Connection=True;"); } } |
Now for this first we will crate a model class file and add the below code into it class file. Here the class file name i have taken is Employee.
using
System; using
System.Collections.Generic; using
System.Linq; using
System.Threading.Tasks; namespace Project.Models {
public class EmployeeModel
{ public List<EmplDetail> EmplDetailList { get; set; }
}
public class EmplDetail
{ public int Id { get; set; } public string EmployeeName { get; set; } public string Designation { get; set; } public string Department { get; set; } public int?
Salery { get; set; }
} } |
[HttpGet] public IActionResult Index() { return View(); } |
@model Project.Models.EmployeeModel @{
ViewData["Title"] = "Home Page"; } <table border="1">
<thead> <tr> <th>ID</th> <th>EMPLOYEE
NAME</th> <th>DEPARMENT</th> <th>DESIGNATION</th> <th>SALERY</th> </tr>
</thead>
<tbody> @foreach (var item in
Model.EmplDetailList) { <tr> <td>@item.Id</td> <td>@item.EmployeeName</td> <td>@item.Department</td> <td>@item.Designation</td> <td>@item.Salery</td> </tr> }
</tbody> </table> |
Downloa
0 comments:
Please let me know your view