Content

  • Dependency Injection
  • Using ApplicationDbContext in Controller
  • Select data from Database using EF Core
  • Creating View with Template & Model
  • [HttpGet] & [HttpPost] attributes
  • asp-for attribute
  • Insert data in Database using EF Core
  • Create links to redirect

Dependency Injection

  • Dependency Injection (DI) is a design pattern used to manage dependencies between objects.
  • It allows you to decouple components by providing dependencies rather than having them create their own.
  • .NET Core provides a built-in dependency injection container, which is responsible for managing the lifetime and resolution of services.
  • Services can have different lifetimes: transient, scoped, and singleton. This determines how instances of services are created and managed by the DI container.
  • The preferred method for injecting dependencies into classes is through constructor injection. Dependencies are provided as constructor parameters.

Lifetimes of Services

  • Transient: Transient services are created each time they are requested.
  • Scoped: Scoped services are created once per client request (i.e., per HTTP request).
  • Singleton: Singleton services are created only once during the lifetime of the application.

Using ApplicationDbContext class in Controller

  • Create ApplicationDbContext field in Controller
  • Inject ApplicationDbContext in Controller using constructor

Example:

Controller File

using Microsoft.AspNetCore.Mvc;
using Test.Web.Data;
                    
namespace Test.Web.Controllers
{
    public class StudentController : Controller
    {
        private readonly ApplicationDbContext _context;
                    
        public StudentController(ApplicationDbContext context)
        {
            _context = context;
        }
                    
        public IActionResult Index()
        {
            return View();
        }
    }
}

Select data from Database using EF Core

We can select data from database using ToList method

Example:

Controller File

using Microsoft.AspNetCore.Mvc;
using Test.Web.Data;
using Test.Web.Models;
    
namespace Test.Web.Controllers
{
    public class StudentController : Controller
    {
        private readonly ApplicationDbContext _context;
    
        public StudentController(ApplicationDbContext context)
        {
            _context = context;
        }
    
        public IActionResult Index()
        {
            var students = _context.Students.ToList();
            return View(students);
        }
            
    }
}

Creating View with Template & Model

Right click on Method Name -> Add View -> Razor View -> Select Template -> Select Model Class -> Add

Example:

View File

@model IEnumerable<Test.Web.Models.Students>

@{
    ViewData["Title"] = "Index";
}
    
<h1>Index</h1>
    
<p>
    <a asp-action="Create">Create New</a>
</p>
<table class="table">
    <thead>
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.Id)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Name)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.City)
            </th>
            <th></th>
        </tr>
    </thead>
    <tbody>
@foreach (var item in Model) {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.Id)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Name)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.City)
            </td>
            <td>
                @Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
                @Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
                @Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
            </td>
        </tr>
}
    </tbody>
</table>

[HttpGet] & [HttpPost] attributes

  • [HttpGet] : It is typically used for actions that retrieve data or perform read-only operations.
  • [HttpPost] : It is commonly used for actions that submit OR modify data

asp-for attribute

  • In Razor views, the asp-for attribute is used to bind HTML form elements to properties of a model. It's part of the Razor syntax that simplifies data binding and reduces the likelihood of errors when working with form elements.
  • It sets - type,id,name,value attributes for HTML elements

Insert data in Database using EF Core

Steps

  1. Add Create[HttpGet] method in Controller
  2. Add Razor View with Template(List) and Model
  3. Update View if required
  4. Add Create[HttpPost] method in Controller, use Add method to insert model in database

Example:

Controller File

using Microsoft.AspNetCore.Mvc;
using Test.Web.Data;
using Test.Web.Models;
    
namespace Test.Web.Controllers
{
    public class StudentController : Controller
    {
        private readonly ApplicationDbContext _context;
    
        public StudentController(ApplicationDbContext context)
        {
            _context = context;
        }
    
        public IActionResult Index()
        {
            var students = _context.Students.ToList();
            return View(students);
        }
        [HttpGet]
        public IActionResult Create()
        {
            return View();
        }
    
        [HttpPost]
        public IActionResult Create(Students student)
        {
            _context.Students.Add(student);
            _context.SaveChanges();
    
            //after adding new student,redirecting to the student list i.e. Index method
            return RedirectToAction("Index");
        }
    }
}

View File

@model Test.Web.Models.Students
@{
    ViewData["Title"] = "Create";
}
    
<h1>Add New Student</h1>
    
    
<hr />
<div class="row">
    <div class="col-md-4">
        <form asp-action="Create">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
                
            <div class="form-group">
                <label asp-for="Name" class="control-label"></label>
                <input asp-for="Name" class="form-control" />
                <span asp-validation-for="Name" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="City" class="control-label"></label>
                <input asp-for="City" class="form-control" />
                <span asp-validation-for="City" class="text-danger"></span>
            </div>
            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-primary" />
            </div>
        </form>
    </div>
</div>
    
<div>
    <a asp-action="Index">Back to List</a>
</div>

Create links to redirect

Example: View File

<li class="nav-item">
    @* asp-controller- Controller name
    asp-action- Action/Method name *@
    <a class="nav-link text-dark" asp-area="" asp-controller="Student" asp-action="Index">Student List</a>
</li>