ASP.NET MVC > Entity Framework

List the data from database in ASP.NET MVC

How to list the data from database in ASP.NET MVC?


To list the data from the database, we can use the default scaffolding template generated while we create Controller and View based on the Model (Explained while how to scaffold Controller and View, the view pages uses bootstrap classes to make it mobie / screen friendly pages).

Let’s understand how list of data works in the Index action method of the controller that is responsible to show records from the database.

We will be using Model for the below database table where AutoId is the auto increment field. Remaining fields are self-explanatory.

The model code for above database table structure is below

MODEL CODE

    public class PersonalDetail
    {
        [Key]

[DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOpt
ion.Identity)]
        public int AutoId { get; set; }

        [StringLength(20, MinimumLength = 4, ErrorMessage = "Must be at least 4
characters long.")]
        [Display(Name= "First Name")]
        public string FirstName { get; set; }

        [Required(ErrorMessage = "Please write your LastName")]
        [Display(Name = "Last Name")]
        public string LastName { get; set; }

        public int Age { get; set; }

        [Display(Name = "Is Active?")]
        public bool Active { get; set; }
    }
}

If you have problem understanding model class, please read Model related posts above to understand above Model class completely.

We have already gone through steps on how to scaffold Controller template and View based on the Model in the previous posts. If we follow that post, we will be getting Index action method in the PersonalDetailsController and Index view in the ~/Views/PersonalDetails/Index.cshmlt.

CONTROLLER CODE

private ApplicationDbContext db = new ApplicationDbContext();

// GET: PersonalDetails
  public ActionResult Index()
  {
      return View(db.PersonalDetails.ToList());
  }

The above method gets the db object that is nothing but the ApplicationDbContext (ADO.NET Entity Framework) object and calls the PersonalDetails (this is the property in the IdentityModel.cs of ApplicationDbContext class that gets created when we scaffold the Controller and View from Model).

This returns all records from the PersonalDetails database table and convert them into List and returns to the View.

INDEX VIEW CODE

    @model IEnumerable<webapplication1.models.personaldetail>
    
    @{
        ViewBag.Title = "Index";
    }
    
    <h2>Index</h2>
    
    <p>
        @Html.ActionLink("Create New", "Create")
    </p>
    <table class="table">
        <tr>
            <th>@Html.DisplayNameFor(model => model.FirstName)
            </th>
            <th>@Html.DisplayNameFor(model => model.LastName)
            </th>
            <th>@Html.DisplayNameFor(model => model.Age)
            </th>
            <th>@Html.DisplayNameFor(model => model.Active)
            </th>
            <th></th>
        </tr>
        @foreach (var item in Model) {
        <tr>
            <td>@Html.DisplayFor(modelItem => item.FirstName)
            </td>
            <td>@Html.DisplayFor(modelItem => item.LastName)
            </td>
            <td>@Html.DisplayFor(modelItem => item.Age)
            </td>
            <td>@Html.DisplayFor(modelItem => item.Active)
            </td>
            <td>@Html.ActionLink("Edit", "Edit", new { id=item.AutoId }) |
                @Html.ActionLink("Details", "Details", new { id=item.AutoId }) |
                @Html.ActionLink("Delete", "Delete", new { id=item.AutoId })
            </td>
        </tr>
        }
    </table>

The above Index view has IEnumerable<WebApplication1.Models.PersonalDetails> Model and then we are using HTML table element to create header of the list and then iterating through the Model (that is nothing but the collection of PersonalDetails).

Here

  • @Html.DisplayNameFor(model => model.FirstName) is used to write the heading of the column that is nothing but the Name value of Display attribute for a Model property, if Display property is not specified then Model property name is written.
  • @Html.DisplayFor(modelItem => item.FirstName) is used to write the value of the Model property.
  • The last column of the HTML table is three links Edit, Details and Delete that redirect to respective Views.
=> is a Lamda expression, a way to retrieve the property of the Model.
The output of the above view looks like below.
 Views: 7819 | Post Order: 100



Write for us