Create an EmployeeManager Controller

The Employee Manager application’s CRUD functionality occurs inside a controller class EmployeeManagerController. To add this class, create the Controllers folder under the project root and add a controller class named EmployeeManagerController using the Add New Item dialog

Step 1 : Create the Controllers folder

Step 2 : Add a new controller by right-clicking on the Controllers folder in your project and selecting Add | Controller, and name it EmployeeManagerController

Step 3 : Add the following lines


...
using Microsoft.AspNetCore.Mvc.Rendering;
using EmployeeManager.Models;
...
private AppDbContext db = null;

public EmployeeManagerController(AppDbContext db)
{
    this.db = db;
}

private void FillCountries()
{
    List<SelectListItem> countries = (from c in db.Countries
                                        orderby c.Name ascending select new SelectListItem() { Text = c.Name, Value = c.Name }).ToList();

    ViewBag.Countries = countries;
}

public IActionResult List()
{
    List<Employee> model = (from e in db.Employees
                            orderby e.EmployeeID
                            select e).ToList();
    return View(model);
}
public IActionResult Insert()
{
    FillCountries();
    return View();
}

[HttpPost]
public IActionResult Insert(Employee model)
{
    FillCountries();
    if (ModelState.IsValid)
    {
        db.Employees.Add(model);
        db.SaveChanges();
        ViewBag.Message = "Employee inserted successfully";
    }
    return View(model);
}

public IActionResult Update(int id)
{
    FillCountries();

    Employee model = db.Employees.Find(id);

    return View(model);
}


[HttpPost]
public IActionResult Update(Employee model)
{
    FillCountries();

    if (ModelState.IsValid)
    {
        db.Employees.Update(model);
        db.SaveChanges();
        ViewBag.Message = "Employee updated successfully";
    }
    return View(model);
}

[ActionName("Delete")]
public IActionResult ConfirmDelete(int id)
{
    Employee model = db.Employees.Find(id);

    return View(model);
}


[HttpPost]
public IActionResult Delete(int employeeID)
{
    Employee model = db.Employees.Find(employeeID);
    db.Employees.Remove(model);
    db.SaveChanges();
    TempData["Message"] = "Employee deleted successfully";
    return RedirectToAction("List");
}

Step 4 :Step 1 : Update the Startup.cs files


public void ConfigureServices(IServiceCollection services)
{
    services.AddControllersWithViews();
    ...
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    ...
    app.UseEndpoints(endpoints => {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=EmployeeManager}/{action=List}/{id?}");
    });
}

Add Comment