CRUD Operation With Image Upload In ASP.NET Core 5 MVC

Today in this article I am going to show you CURD operation with ASP.NET Core 5 MVC. We all know that Microsoft has released the version of core 5 which is now called .NET 5. So I thought why not create an article on ASP.NET core 5 MVC. It is cross platform, and some of its features are mentioned below. For more information about features you can refer to Microsoft msdn documents. Here I am going in to perform CURD with image upload. Code
  • C# updates.
  • F# updates.
  • Visual Basic updates.
  • System.Text.Json new features.
  • Single file apps.
  • App trimming.
  • Windows ARM64 and ARM64 intrinsics.
  • Tooling support for dump debugging
  • The runtime libraries are 80% annotated for nullable reference types
  • Performance improvements,

    • Garbage Collection (GC)
    • System.Text.Json
    • System.Text.RegularExpressions
    • Async ValueTask pooling
    • Container size optimizations
    • Many more areas
Step 1
 
Visual Studio 2019 16.8 or later with the ASP.NET and web development workload.
 
Step 2 
 
 
Step 3
 
Start Visual Studio and select Create a new project in the Create a new project dialog.
 
CURD Operation With Image Upload In ASP.NET Core 5 MVC
 
Select ASP.NET Core Web Application > Next.
 
CURD Operation With Image Upload In ASP.NET Core 5 MVC
 
In the Configure your new project dialog, enter CURDOperationWithImageUploadCore5_Demo for Project name. It's important to use this exact name including capitalization, so each namespace matches when the code is copied. Select Create.
 
CURD Operation With Image Upload In ASP.NET Core 5 MVC
 
In the Create a new ASP.NET Core web application dialog, select,
  1. .NET Core and ASP.NET Core 5.0 in the dropdowns.
  2. ASP.NET Core Web App (Model-View-Controller).
  3. Create 
CURD Operation With Image Upload In ASP.NET Core 5 MVC
 
Step 4
 
Right-click the Models folder > Add > Class. Name the file Speaker.cs.
  1. using System;  
  2. using System.ComponentModel.DataAnnotations;  
  3.   
  4. namespace CURDOperationWithImageUploadCore5_Demo.Models  
  5. {  
  6.     public class Speaker  
  7.     {  
  8.         [Key]  
  9.         public int Id { getset; }  
  10.   
  11.         [Required]  
  12.         [StringLength(100)]  
  13.         [Display(Name = "Name")]  
  14.         public string SpeakerName { getset; }  
  15.   
  16.         [Required]  
  17.         [StringLength(100)]  
  18.         public string Qualification { getset; }  
  19.   
  20.         [Required]  
  21.         [StringLength(100)]  
  22.         public int Experience { getset; }  
  23.   
  24.         [Required]  
  25.         [DataType(DataType.Date)]  
  26.         [Display(Name = "Date")]  
  27.         public DateTime SpeakingDate { getset; }  
  28.   
  29.         [Required]  
  30.         [DataType(DataType.Time)]  
  31.         [Display(Name = "Time")]  
  32.         public DateTime SpeakingTime { getset; }  
  33.   
  34.         [Required]  
  35.         [StringLength(255)]  
  36.         public string Venue { getset; }  
  37.   
  38.         [Required]  
  39.         [Display(Name = "Image")]  
  40.         public string ProfilePicture { getset; }  
  41.     }  
  42. }   
Step 5
 
From the Tools menu, select NuGet Package Manager and install the following package.
  • Microsoft.EntityFrameworkCore
  • Microsoft.EntityFrameworkCore.SqlServer
  • Microsoft.EntityFrameworkCore.Tools 
Step 6
 
In the Solution Explorer, Create a Data folder. Create a database context class.
  1. using CURDOperationWithImageUploadCore5_Demo.Models;  
  2. using Microsoft.EntityFrameworkCore;  
  3.   
  4. namespace CURDOperationWithImageUploadCore5_Demo.Data  
  5. {  
  6.     public class ApplicationDbContext : DbContext  
  7.     {  
  8.         public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) :  
  9.             base(options)  
  10.         {  
  11.   
  12.         }  
  13.         public DbSet<Speaker> Speakers { getset; }  
  14.     }  
  15. }  
Step 7
 
Register the database context. Add the following using statements at the top of Startup.cs
  1. using Microsoft.EntityFrameworkCore;  
  2. using CURDOperationWithImageUploadCore5_Demo.Data;   
Add the following highlighted code in Startup.ConfigureServices
  1. services.AddDbContext<ApplicationDbContext>(options =>options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));  
Step 8
 
Add a database connection string. Add a connection string to the appsettings.json file
  1. "ConnectionStrings": {  
  2. "DefaultConnection""Server=(localdb)\\mssqllocaldb;Database=SpeakerDB;Trusted_Connection=True;MultipleActiveResultSets=true"  
  3. }   
Step 9
 
Use the scaffolding tool to produce Create, Read, Update, and Delete (CRUD) pages for the movie model. In Solution Explorer, right-click the Controllers folder > Add > New Scaffolded Item.
 
CURD Operation With Image Upload In ASP.NET Core 5 MVC
 
In the Add Scaffold dialog, select MVC Controller with views, using Entity Framework > Add.
 
CURD Operation With Image Upload In ASP.NET Core 5 MVC
 
Complete the Add Controller dialog,
  • Model class: Speaker (Speaker.Models)
  • Data context class: ApplicationDbContext (ApplicationDbContext.Data)
CURD Operation With Image Upload In ASP.NET Core 5 MVC
  • Views: Keep the default of each option checked
  • Controller name: Keep the default SpeakersController
  • Select Add
Visual Studio creates
  • A movies controller (Controllers/SpeakerController.cs)
  • Razor view files for Create, Delete, Details, Edit, and Index pages (Views/Speakers/*.cshtml)
Complete Controller Code
  1. using CURDOperationWithImageUploadCore5_Demo.Data;  
  2. using CURDOperationWithImageUploadCore5_Demo.Models;  
  3. using CURDOperationWithImageUploadCore5_Demo.ViewModels;  
  4. using Microsoft.AspNetCore.Hosting;  
  5. using Microsoft.AspNetCore.Mvc;  
  6. using Microsoft.EntityFrameworkCore;  
  7. using System;  
  8. using System.IO;  
  9. using System.Linq;  
  10. using System.Threading.Tasks;  
  11.   
  12. namespace CURDOperationWithImageUploadCore5_Demo.Controllers  
  13. {  
  14.     public class SpeakersController : Controller  
  15.     {  
  16.         private readonly ApplicationDbContext db;  
  17.         private readonly IWebHostEnvironment webHostEnvironment;  
  18.         public SpeakersController(ApplicationDbContext context, IWebHostEnvironment hostEnvironment)  
  19.         {  
  20.             db = context;  
  21.             webHostEnvironment = hostEnvironment;  
  22.         }  
  23.   
  24.         public async Task<IActionResult> Index()  
  25.         {  
  26.             return View(await db.Speakers.ToListAsync());  
  27.         }  
  28.   
  29.         public async Task<IActionResult> Details(int? id)  
  30.         {  
  31.             if (id == null)  
  32.             {  
  33.                 return NotFound();  
  34.             }  
  35.   
  36.             var speaker = await db.Speakers  
  37.                 .FirstOrDefaultAsync(m => m.Id == id);  
  38.   
  39.             var speakerViewModel = new SpeakerViewModel()  
  40.             {  
  41.                 Id = speaker.Id,  
  42.                 SpeakerName = speaker.SpeakerName,  
  43.                 Qualification = speaker.Qualification,  
  44.                 Experience = speaker.Experience,  
  45.                 SpeakingDate = speaker.SpeakingDate,  
  46.                 SpeakingTime = speaker.SpeakingTime,  
  47.                 Venue = speaker.Venue,  
  48.                 ExistingImage = speaker.ProfilePicture  
  49.             };  
  50.   
  51.             if (speaker == null)  
  52.             {  
  53.                 return NotFound();  
  54.             }  
  55.   
  56.             return View(speaker);  
  57.         }  
  58.   
  59.         public IActionResult Create()  
  60.         {  
  61.             return View();  
  62.         }  
  63.   
  64.         [HttpPost]  
  65.         [ValidateAntiForgeryToken]  
  66.         public async Task<IActionResult> Create(SpeakerViewModel model)  
  67.         {  
  68.             if (ModelState.IsValid)  
  69.             {  
  70.                 string uniqueFileName = ProcessUploadedFile(model);  
  71.                 Speaker speaker = new Speaker  
  72.                 {  
  73.                     SpeakerName = model.SpeakerName,  
  74.                     Qualification = model.Qualification,  
  75.                     Experience = model.Experience,  
  76.                     SpeakingDate = model.SpeakingDate,  
  77.                     SpeakingTime = model.SpeakingTime,  
  78.                     Venue = model.Venue,  
  79.                     ProfilePicture = uniqueFileName  
  80.                 };  
  81.   
  82.                 db.Add(speaker);  
  83.                 await db.SaveChangesAsync();  
  84.                 return RedirectToAction(nameof(Index));  
  85.             }  
  86.             return View(model);  
  87.         }  
  88.   
  89.         public async Task<IActionResult> Edit(int? id)  
  90.         {  
  91.             if (id == null)  
  92.             {  
  93.                 return NotFound();  
  94.             }  
  95.   
  96.             var speaker = await db.Speakers.FindAsync(id);  
  97.             var speakerViewModel = new SpeakerViewModel()  
  98.             {  
  99.                 Id = speaker.Id,  
  100.                 SpeakerName = speaker.SpeakerName,  
  101.                 Qualification = speaker.Qualification,  
  102.                 Experience = speaker.Experience,  
  103.                 SpeakingDate = speaker.SpeakingDate,  
  104.                 SpeakingTime = speaker.SpeakingTime,  
  105.                 Venue = speaker.Venue,  
  106.                 ExistingImage = speaker.ProfilePicture  
  107.             };  
  108.   
  109.             if (speaker == null)  
  110.             {  
  111.                 return NotFound();  
  112.             }  
  113.             return View(speakerViewModel);  
  114.         }  
  115.   
  116.         [HttpPost]  
  117.         [ValidateAntiForgeryToken]  
  118.         public async Task<IActionResult> Edit(int id, SpeakerViewModel model)  
  119.         {  
  120.             if (ModelState.IsValid)  
  121.             {  
  122.                 var speaker = await db.Speakers.FindAsync(model.Id);  
  123.                 speaker.SpeakerName = model.SpeakerName;  
  124.                 speaker.Qualification = model.Qualification;  
  125.                 speaker.Experience = model.Experience;  
  126.                 speaker.SpeakingDate = model.SpeakingDate;  
  127.                 speaker.SpeakingTime = model.SpeakingTime;  
  128.                 speaker.Venue = model.Venue;  
  129.   
  130.                 if (model.SpeakerPicture != null)  
  131.                 {  
  132.                     if (model.ExistingImage != null)  
  133.                     {  
  134.                         string filePath = Path.Combine(webHostEnvironment.WebRootPath, "Uploads", model.ExistingImage);  
  135.                         System.IO.File.Delete(filePath);  
  136.                     }  
  137.   
  138.                     speaker.ProfilePicture = ProcessUploadedFile(model);  
  139.                 }  
  140.                 db.Update(speaker);  
  141.                 await db.SaveChangesAsync();  
  142.                 return RedirectToAction(nameof(Index));  
  143.             }  
  144.             return View();  
  145.         }  
  146.   
  147.         public async Task<IActionResult> Delete(int? id)  
  148.         {  
  149.             if (id == null)  
  150.             {  
  151.                 return NotFound();  
  152.             }  
  153.   
  154.             var speaker = await db.Speakers  
  155.                 .FirstOrDefaultAsync(m => m.Id == id);  
  156.   
  157.             var speakerViewModel = new SpeakerViewModel()  
  158.             {  
  159.                 Id = speaker.Id,  
  160.                 SpeakerName = speaker.SpeakerName,  
  161.                 Qualification = speaker.Qualification,  
  162.                 Experience = speaker.Experience,  
  163.                 SpeakingDate = speaker.SpeakingDate,  
  164.                 SpeakingTime = speaker.SpeakingTime,  
  165.                 Venue = speaker.Venue,  
  166.                 ExistingImage = speaker.ProfilePicture  
  167.             };  
  168.             if (speaker == null)  
  169.             {  
  170.                 return NotFound();  
  171.             }  
  172.   
  173.             return View(speakerViewModel);  
  174.         }  
  175.   
  176.         [HttpPost, ActionName("Delete")]  
  177.         [ValidateAntiForgeryToken]  
  178.         public async Task<IActionResult> DeleteConfirmed(int id)  
  179.         {  
  180.             var speaker = await db.Speakers.FindAsync(id);  
  181.             var CurrentImage = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot\\images", speaker.ProfilePicture);  
  182.             db.Speakers.Remove(speaker);  
  183.             if (await db.SaveChangesAsync() > 0)  
  184.             {  
  185.                 if (System.IO.File.Exists(CurrentImage))  
  186.                 {  
  187.                     System.IO.File.Delete(CurrentImage);  
  188.                 }  
  189.             }  
  190.             return RedirectToAction(nameof(Index));  
  191.         }  
  192.   
  193.         private bool SpeakerExists(int id)  
  194.         {  
  195.             return db.Speakers.Any(e => e.Id == id);  
  196.         }  
  197.   
  198.         private string ProcessUploadedFile(SpeakerViewModel model)  
  199.         {  
  200.             string uniqueFileName = null;  
  201.   
  202.             if (model.SpeakerPicture != null)  
  203.             {  
  204.                 string uploadsFolder = Path.Combine(webHostEnvironment.WebRootPath, "Uploads");  
  205.                 uniqueFileName = Guid.NewGuid().ToString() + "_" + model.SpeakerPicture.FileName;  
  206.                 string filePath = Path.Combine(uploadsFolder, uniqueFileName);  
  207.                 using (var fileStream = new FileStream(filePath, FileMode.Create))  
  208.                 {  
  209.                     model.SpeakerPicture.CopyTo(fileStream);  
  210.                 }  
  211.             }  
  212.   
  213.             return uniqueFileName;  
  214.         }  
  215.     }  
  216. }   
Step 10
 
Initial migration. Use the EF Core Migrations feature to create the database. Migrations is a set of tools that let you create and update a database to match your data model. 
 
From the Tools menu, select NuGet Package Manager > Package Manager Console (PMC).
  1. Add-Migration InitialModel  
  2. Update-Database  
Step 11
 
Create ViewModels folder for UploadImageViewModel,EditImageViewModel and SpeakerViewModel.
 
UploadImageViewModel
  1. using Microsoft.AspNetCore.Http;  
  2. using System.ComponentModel.DataAnnotations;  
  3.   
  4. namespace CURDOperationWithImageUploadCore5_Demo.ViewModels  
  5. {  
  6.     public class UploadImageViewModel  
  7.     {  
  8.         [Required]  
  9.         [Display(Name = "Image")]  
  10.         public IFormFile SpeakerPicture { getset; }  
  11.     }  
  12. }  
EditImageViewModel
  1. namespace CURDOperationWithImageUploadCore5_Demo.ViewModels  
  2. {  
  3.     public class EditImageViewModel : UploadImageViewModel  
  4.     {  
  5.         public int Id { getset; }  
  6.         public string ExistingImage { getset; }  
  7.     }  
  8. }  
 SpeakerViewModel
  1. using System;  
  2. using System.ComponentModel.DataAnnotations;  
  3.   
  4. namespace CURDOperationWithImageUploadCore5_Demo.ViewModels  
  5. {  
  6.     public class SpeakerViewModel : EditImageViewModel  
  7.     {  
  8.         [Required]  
  9.         [Display(Name = "Name")]  
  10.         public string SpeakerName { getset; }  
  11.   
  12.         [Required]  
  13.         public string Qualification { getset; }  
  14.   
  15.         [Required]  
  16.         public int Experience { getset; }  
  17.   
  18.         [Required]  
  19.         [DataType(DataType.Date)]  
  20.         [Display(Name = "Date")]  
  21.         public DateTime SpeakingDate { getset; }  
  22.   
  23.         [Required]  
  24.         [DataType(DataType.Time)]  
  25.         [Display(Name = "Time")]  
  26.         public DateTime SpeakingTime { getset; }  
  27.   
  28.         [Required]  
  29.         public string Venue { getset; }  
  30.     }  
  31. }  
Step 12
 
Create Uploads folder in wwwroot folder to upload images.
 
Step 13
 
Built and Run your project Ctrl+F5
 
Index List of Speaker 
 
CURD Operation With Image Upload In ASP.NET Core 5 MVC
Speaker Details
 
CURD Operation With Image Upload In ASP.NET Core 5 MVC
 
New Speaker 
 
CURD Operation With Image Upload In ASP.NET Core 5 MVC
 
Edit Speaker Details
 
CURD Operation With Image Upload In ASP.NET Core 5 MVC
 
Delete Speaker  
 
CURD Operation With Image Upload In ASP.NET Core 5 MVC
 

Conclusion 

 
This article was about create, details, edit and delete with image file upload. I hope enjoyed the article. Happy coding....CURD Operation With Image Upload In ASP.NET Core 5 MVC