asp.net mvc crud project source code Archives - Tech Insights Unveiling Tomorrow's Tech Today, Where Innovation Meets Insight Thu, 15 Dec 2022 11:47:13 +0000 en-US hourly 1 https://wordpress.org/?v=6.6.2 https://i0.wp.com/reactconf.org/wp-content/uploads/2023/11/cropped-reactconf.png?fit=32%2C32&ssl=1 asp.net mvc crud project source code Archives - Tech Insights 32 32 230003556 How to create CRUD Operation in Asp.net Core MVC C# https://reactconf.org/how-to-create-crud-operation-in-asp-net-core-mvc-c/ https://reactconf.org/how-to-create-crud-operation-in-asp-net-core-mvc-c/#comments Thu, 15 Dec 2022 11:47:13 +0000 https://labpys.com/?p=501 In this article, we will learn how to create CRUD (Create, Read, Update, Delete) Operation using Asp.Net Core MVC C# with .Net6.0, Entity Framework Core and SQL. Then how to …

The post How to create CRUD Operation in Asp.net Core MVC C# appeared first on Tech Insights.

]]>
In this article, we will learn how to create CRUD (Create, Read, Update, Delete) Operation using Asp.Net Core MVC C# with .Net6.0, Entity Framework Core and SQL. Then how to use that web app to perform CRUD Operations.

Prerequisites

  • Download and install .Net Core 6.0 SDK from here
  • Download and Install Microsoft Visual Studio 2022 from here
  • Sql-Server

Previous Article checkout https://labpys.com/how-to-create-login-page-using-asp-net-core-mvc-c-with-database

Create an ASP.NET Core MVC Project

Open visual studio, Go to File menu and click on New and select Project. Then new project window, select ASP.NET Core Web Application (Model-View-Controller) template.

Enter  project name and click create.

Install NuGet packages

We need to install NuGet Packages for the right click on solution and select Manage NuGet Packages for solution  

  • Microsoft Entity Framework Core Sql Server
  • Microsoft Entity Framework Core Tools

Configure appsettings.json

 The connection string “connectionstr” is saved in appSettings.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "ConnectionStrings":{
    "connectionstr": "Server=(local)\\MSSQL;Database=InventoryDB;Trusted_Connection=True;MultipleActiveResultSets=true"
  },
  "AllowedHosts": "*"
}

Create Model

Create new model class with add more properties like FirstName, LastName

using System.ComponentModel.DataAnnotations;

namespace CRUDOperation.Models
{
    public class Employee
    {
        [Key]
        public int id { get; set; }      
        public string? firstName { get; set; }      
        public string? lastName { get; set; }
        public string? job { get; set; }
        public float?  salary { get; set; }
        public DateTime? hiredate { get; set; }

    }
}

Create Dbcontext Class

DbContext is an class in Entity Framework API. It is a bridge between your domain class and the database. DbContext is the class that is responsible for interacting with the database. As per Microsoft  “A DbContext instance represents a combination of the Unit Of Work and Repository pattern such that it can be used to query from a database”

using Microsoft.EntityFrameworkCore;

namespace CRUDOperation.Models
{
    public class Empdbcontext : DbContext
    {
        public Empdbcontext(DbContextOptions<Empdbcontext> options):base(options)
        {

        }
        public DbSet<Employee> Employee { get; set; }


    }
}

Create Repositories

Now create repository folder , in this folder create two class  .Create Interface  IEmployee.cs file and Employeedetail.cs

IEmployee.cs

using CRUDOperation.Models; 
namespace CRUDOperation.Repository
{
    public interface IEmployee
    {
        Task<int> CreateEmployee(Employee employee);
        Task<int> UpdateEmployee(Employee employee);
        Task<int> DeleteEmployee(int? id);
        Employee GetEmployeeById(int id);
        Task<IEnumerable<Employee>> GetEmployee();            

    }
}

Employeedetail.cs

using CRUDOperation.Models;
using Microsoft.EntityFrameworkCore;
using CRUDOperation.ViewModel;

namespace CRUDOperation.Repository
{
    public class Employeedetail : IEmployee
    {
        private readonly Empdbcontext _context;

        public Employeedetail(Empdbcontext context)
        {
            _context = context;
        }

        public async Task<int> CreateEmployee(Employee employee)
        {
            if (employee != null)
            {
                await _context.Employee.AddAsync(employee);
                await _context.SaveChangesAsync();
                return employee.id;
            }
            return 0;
        }

        public async Task<int> DeleteEmployee(int? id)
        {
            int Getresult = 0;

            if (id!=null)
            {
                var rec_id = await _context.Employee.FirstOrDefaultAsync(Empid => Empid.id == id);
                if(rec_id !=null)
                {
                    _context.Remove(_context.Employee.Single(Empid => Empid.id == id));
                    Getresult = await _context.SaveChangesAsync();
                }
                return Getresult;
            
            }
            return Getresult;
        }
         

        public  async  Task<int> UpdateEmployee(Employee employee)
        {
            if (employee != null)
            {
               _context.Employee.Update(employee);
               await _context.SaveChangesAsync();
               return employee.id;
            }
            return 0;
        }

         public async Task<IEnumerable<Employee>> GetEmployee()
        {
            if (_context != null)
            {
                return await _context.Employee.ToListAsync();
            }

            return null;
        }

        public  Employee GetEmployeeById(int id)
        {

         if (_context!=null)
            {
              return  _context.Employee.FirstOrDefault(e=>e.id==id);
               
            }
            return null;
        }        
    }
}

Configure Startup Class

using CRUDOperation.Models;
using Microsoft.EntityFrameworkCore; 
using CRUDOperation.Repository;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();

builder.Services.AddDbContext<Empdbcontext>(con => con.UseSqlServer(builder.Configuration.GetConnectionString("connectionstr")));
 
builder.Services.AddTransient<IEmployee,Employeedetail>();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

Migration

Then Now create Database through Migration. Go to Tools>NuGet Package Manager>Package Manager Console then execute the following commands.

Add-Migration “Initial Create”

Update-Database

Create View Model

EmployeeViewmodel.cs

using CRUDOperation.Repository;
using CRUDOperation.Models;

namespace CRUDOperation.ViewModel
{
    public class EmployeeViewmodel  
    {
          
        public Employee viewEmployee { get; set; }
        public int id { get; set; }
        public string? firstName { get; set; }
        public string? lastName { get; set; }
        public string? job { get; set; }
        public float? salary { get; set; }
        public DateTime? hiredate { get; set; }
       
    }
}

Create Controller

using CRUDOperation.Models;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
using CRUDOperation.Repository;
using CRUDOperation.ViewModel;

namespace CRUDOperation.Controllers
{
    public class HomeController : Controller
    {
        private readonly IEmployee employee ;

        public HomeController(IEmployee employee)
        {
            this.employee = employee;
        }

        public IActionResult Index()
        {
            try
            {
                var Getempresult = employee.GetEmployee().Result;
                ViewBag.Employee = Getempresult;
                return View();
            }
            catch (Exception)
            {
                throw;
            }
            return View();
        }

        public IActionResult Create()
        {
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult Create(Employee empmodel)
        {
            if (ModelState.IsValid)
            {
              employee.CreateEmployee(empmodel);
            }
            ViewBag.message = "Data Saved Successfully..";

            ModelState.Clear();    
            return View();
        }

        public IActionResult  Edit(int id)
        {
            EmployeeViewmodel empview = new EmployeeViewmodel()
            {
                viewEmployee = employee.GetEmployeeById(id)
            }; 
            return View(empview);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult Edit(EmployeeViewmodel viewEmployee)
        {
            Employee empmodel = new Employee()
            {
                id=viewEmployee.id,
                firstName = viewEmployee.firstName,
                lastName = viewEmployee.lastName,
                job = viewEmployee.job,
                salary= viewEmployee.salary,
                hiredate= viewEmployee.hiredate
            };
            var result = employee.UpdateEmployee(empmodel);
            ModelState.Clear();
            return View();
        }

        public IActionResult Delete(int id)
        {
            EmployeeViewmodel empview = new EmployeeViewmodel()
            {
                viewEmployee = employee.GetEmployeeById(id)
            };
            return View(empview);
        }

        [HttpPost]
        [AutoValidateAntiforgeryToken]
        public IActionResult Delete(EmployeeViewmodel viewmodel)
        {
            var result = employee.DeleteEmployee(viewmodel.id);
            
            return RedirectToAction(nameof(Index));
        }


        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}

Customize View Index

Index.cshtml

@{
    ViewData["Title"] = "Home Page";
}
<div>
<a class="text-center">
       <div class="container">
             <a asp-area="" asp-controller="Home" asp-action="Create">Create New</a>
        </div>   
   <table class="table table-responsive bg-light">
       <thead>
           <tr>
           <td>First Name</td>
           <td>Last Name</td>
           <td>Designation</td>
           <td>Salary</td>
           <td>Joining Date</td>   
           <td>Action</td>   
           </tr>
       </thead>
       <tbody>
       @foreach (var item in ViewBag.Employee)
       {
            <tr>
           <td>@item.firstName</td>
           <td>@item.lastName</td>
           <td>@item.job</td>
           <td>@item.salary</td>
           <td>@item.hiredate</td>
           <td><a asp-controller="Home"  asp-action="Edit"  asp-route-id="@item.id">Edit</a></td>
           <td><a asp-controller="Home" asp-action="Delete" asp-route-id="@item.id">Delete</a></td>
           </tr>
       }
       </tbody>
   </table>
</div>

Create.cshtml

@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
}
@model CRUDOperation.ViewModel.EmployeeViewmodel
 
<h2>@ViewBag.message</h2>
  <div class="container shadow p-5">
    <div class="row pb-2">
        <h2>Add Employee</h2>
    </div>

    <form method="POST"  enctype="multipart/form-data" asp-controller="Home" asp-action="Create" >
      
      <div asp-validation-summary="All"></div>  
       
      <div class="form-row">
        <div class="form-group col-md-6">
            <label asp-for="firstName">First Name</label>
            <input type="text" class="form-control mb-3" asp-for="firstName" placeholder="Enter Employee First Name">
            <span asp-validation-for="firstName" class="aler-danger"></span>
        </div>
        <div class="form-group col-md-6">
            <label asp-for="lastName">Last Name</label>
            <input type="text" class="form-control mb-3" asp-for="lastName" placeholder="Enter Employee Last Name">
            <span asp-validation-for="lastName" class="aler-danger"></span>
        </div>

        <div class="form-group col-md-6">
            <label asp-for="job">Designation</label>
            <input type="text" class="form-control mb-3" asp-for="job" placeholder="Enter Designation">
            <span asp-validation-for="job" class="aler-danger"></span>
        </div>

        <div class="form-group col-md-6">
            <label asp-for="salary">Salary</label>
            <input type="text" class="form-control mb-3" asp-for="salary" placeholder="Enter Salary">
            <span asp-validation-for="salary" class="aler-danger"></span>
        </div>

        <div class="form-group col-md-6">
            <label asp-for="hiredate">Joining Date</label>
            <input type="date" class="form-control mb-3" asp-for="hiredate" placeholder="Enter Joining Date">
            <span asp-validation-for="hiredate" class="aler-danger"></span>
        </div>
      </div>
      <input  type="submit" class="btn btn-lg btn-primary p-2" value="Submit"/>    
    </form>    
</div>

Edit.cshtml

@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
}
@model CRUDOperation.ViewModel.EmployeeViewmodel
<div>
<h2>Update Employee</h2>

    <form method="POST"  enctype="multipart/form-data" asp-controller="Home" asp-action="Edit">
      
     @* <div asp-validation-summary="All"></div>  *@
       
      <div class="form-row">
          <input asp-for="viewEmployee.id" hidden />
        <div class="form-group col-md-6">
            <label asp-for="firstName">First Name</label>
            <input asp-for="viewEmployee.firstName" class="form-control">
            <span asp-validation-for="firstName" class="aler-danger"></span>
        </div>
        <div class="form-group col-md-6">
            <label asp-for="lastName">Last Name</label>
             <input asp-for="viewEmployee.lastName" class="form-control" >
            <span asp-validation-for="lastName" class="aler-danger"></span>
        </div>

        <div class="form-group col-md-6">
            <label asp-for="job">Designation</label>
             <input asp-for="viewEmployee.job" class="form-control">
            <span asp-validation-for="job" class="aler-danger"></span>
        </div>

        <div class="form-group col-md-6">
            <label asp-for="salary">Salary</label>
             <input asp-for="viewEmployee.salary" class="form-control">
            <span asp-validation-for="salary" class="aler-danger"></span>
        </div>

        <div class="form-group col-md-6">
            <label asp-for="hiredate">Joining Date</label>
             <input asp-for="viewEmployee.hiredate" class="form-control">
            <span asp-validation-for="hiredate" class="aler-danger"></span>
        </div>
      </div>
      <br/>
      <button type="submit" class="btn btn-lg btn-primary p-2"><i class="bi bi-file-plus-fill"></i>Submit</button>
    </form>    
</div>

Delete.cshtml

@*
    For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860
*@
@model CRUDOperation.ViewModel.EmployeeViewmodel
<div>
<h2>Delete Employee</h2>

    <form method="POST"  enctype="multipart/form-data" asp-controller="Home" asp-action="Delete">
      
     @* <div asp-validation-summary="All"></div>  *@
       
      <div class="form-row">
          <input asp-for="viewEmployee.id" hidden />
        <div class="form-group col-md-6">
            <label asp-for="firstName">First Name</label>
            <input asp-for="viewEmployee.firstName" class="form-control" readonly>
            <span asp-validation-for="firstName" class="aler-danger"></span>
        </div>
        <div class="form-group col-md-6">
            <label asp-for="lastName">Last Name</label>
             <input asp-for="viewEmployee.lastName" class="form-control" readonly >
            <span asp-validation-for="lastName" class="aler-danger"></span>
        </div>

        <div class="form-group col-md-6">
            <label asp-for="job">Designation</label>
             <input asp-for="viewEmployee.job" class="form-control" readonly>
            <span asp-validation-for="job" class="aler-danger"></span>
        </div>

        <div class="form-group col-md-6">
            <label asp-for="salary">Salary</label>
             <input asp-for="viewEmployee.salary" class="form-control" readonly>
            <span asp-validation-for="salary" class="aler-danger"></span>
        </div>

        <div class="form-group col-md-6">
            <label asp-for="hiredate">Joining Date</label>
             <input asp-for="viewEmployee.hiredate" class="form-control" readonly>
            <span asp-validation-for="hiredate" class="aler-danger"></span>
        </div>
      </div>
      <br/>
      <button type="submit" class="btn btn-lg btn-primary p-2"><i class="bi bi-file-plus-fill"></i>Submit</button>
    </form>
    
</div>

Then build the project and Run.

The post How to create CRUD Operation in Asp.net Core MVC C# appeared first on Tech Insights.

]]>
https://reactconf.org/how-to-create-crud-operation-in-asp-net-core-mvc-c/feed/ 2 501