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
Install .NET 5.0 SDK or later
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. namespace CURDOperationWithImageUploadCore5_Demo.Models
  4. {
  5. public class Speaker
  6. {
  7. [Key]
  8. public int Id { get; set; }
  9. [Required]
  10. [StringLength(100)]
  11. [Display(Name = "Name")]
  12. public string SpeakerName { get; set; }
  13. [Required]
  14. [StringLength(100)]
  15. public string Qualification { get; set; }
  16. [Required]
  17. [StringLength(100)]
  18. public int Experience { get; set; }
  19. [Required]
  20. [DataType(DataType.Date)]
  21. [Display(Name = "Date")]
  22. public DateTime SpeakingDate { get; set; }
  23. [Required]
  24. [DataType(DataType.Time)]
  25. [Display(Name = "Time")]
  26. public DateTime SpeakingTime { get; set; }
  27. [Required]
  28. [StringLength(255)]
  29. public string Venue { get; set; }
  30. [Required]
  31. [Display(Name = "Image")]
  32. public string ProfilePicture { get; set; }
  33. }
  34. }
Step 5
From the Tools menu, select NuGet Package Manager and install the following package.
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. namespace CURDOperationWithImageUploadCore5_Demo.Data
  4. {
  5. public class ApplicationDbContext : DbContext
  6. {
  7. public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) :
  8. base(options)
  9. {
  10. }
  11. public DbSet<Speaker> Speakers { get; set; }
  12. }
  13. }
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. namespace CURDOperationWithImageUploadCore5_Demo.Controllers
  12. {
  13. public class SpeakersController : Controller
  14. {
  15. private readonly ApplicationDbContext db;
  16. private readonly IWebHostEnvironment webHostEnvironment;
  17. public SpeakersController(ApplicationDbContext context, IWebHostEnvironment hostEnvironment)
  18. {
  19. db = context;
  20. webHostEnvironment = hostEnvironment;
  21. }
  22. public async Task<IActionResult> Index()
  23. {
  24. return View(await db.Speakers.ToListAsync());
  25. }
  26. public async Task<IActionResult> Details(int? id)
  27. {
  28. if (id == null)
  29. {
  30. return NotFound();
  31. }
  32. var speaker = await db.Speakers
  33. .FirstOrDefaultAsync(m => m.Id == id);
  34. var speakerViewModel = new SpeakerViewModel()
  35. {
  36. Id = speaker.Id,
  37. SpeakerName = speaker.SpeakerName,
  38. Qualification = speaker.Qualification,
  39. Experience = speaker.Experience,
  40. SpeakingDate = speaker.SpeakingDate,
  41. SpeakingTime = speaker.SpeakingTime,
  42. Venue = speaker.Venue,
  43. ExistingImage = speaker.ProfilePicture
  44. };
  45. if (speaker == null)
  46. {
  47. return NotFound();
  48. }
  49. return View(speaker);
  50. }
  51. public IActionResult Create()
  52. {
  53. return View();
  54. }
  55. [HttpPost]
  56. [ValidateAntiForgeryToken]
  57. public async Task<IActionResult> Create(SpeakerViewModel model)
  58. {
  59. if (ModelState.IsValid)
  60. {
  61. string uniqueFileName = ProcessUploadedFile(model);
  62. Speaker speaker = new Speaker
  63. {
  64. SpeakerName = model.SpeakerName,
  65. Qualification = model.Qualification,
  66. Experience = model.Experience,
  67. SpeakingDate = model.SpeakingDate,
  68. SpeakingTime = model.SpeakingTime,
  69. Venue = model.Venue,
  70. ProfilePicture = uniqueFileName
  71. };
  72. db.Add(speaker);
  73. await db.SaveChangesAsync();
  74. return RedirectToAction(nameof(Index));
  75. }
  76. return View(model);
  77. }
  78. public async Task<IActionResult> Edit(int? id)
  79. {
  80. if (id == null)
  81. {
  82. return NotFound();
  83. }
  84. var speaker = await db.Speakers.FindAsync(id);
  85. var speakerViewModel = new SpeakerViewModel()
  86. {
  87. Id = speaker.Id,
  88. SpeakerName = speaker.SpeakerName,
  89. Qualification = speaker.Qualification,
  90. Experience = speaker.Experience,
  91. SpeakingDate = speaker.SpeakingDate,
  92. SpeakingTime = speaker.SpeakingTime,
  93. Venue = speaker.Venue,
  94. ExistingImage = speaker.ProfilePicture
  95. };
  96. if (speaker == null)
  97. {
  98. return NotFound();
  99. }
  100. return View(speakerViewModel);
  101. }
  102. [HttpPost]
  103. [ValidateAntiForgeryToken]
  104. public async Task<IActionResult> Edit(int id, SpeakerViewModel model)
  105. {
  106. if (ModelState.IsValid)
  107. {
  108. var speaker = await db.Speakers.FindAsync(model.Id);
  109. speaker.SpeakerName = model.SpeakerName;
  110. speaker.Qualification = model.Qualification;
  111. speaker.Experience = model.Experience;
  112. speaker.SpeakingDate = model.SpeakingDate;
  113. speaker.SpeakingTime = model.SpeakingTime;
  114. speaker.Venue = model.Venue;
  115. if (model.SpeakerPicture != null)
  116. {
  117. if (model.ExistingImage != null)
  118. {
  119. string filePath = Path.Combine(webHostEnvironment.WebRootPath, "Uploads", model.ExistingImage);
  120. System.IO.File.Delete(filePath);
  121. }
  122. speaker.ProfilePicture = ProcessUploadedFile(model);
  123. }
  124. db.Update(speaker);
  125. await db.SaveChangesAsync();
  126. return RedirectToAction(nameof(Index));
  127. }
  128. return View();
  129. }
  130. public async Task<IActionResult> Delete(int? id)
  131. {
  132. if (id == null)
  133. {
  134. return NotFound();
  135. }
  136. var speaker = await db.Speakers
  137. .FirstOrDefaultAsync(m => m.Id == id);
  138. var speakerViewModel = new SpeakerViewModel()
  139. {
  140. Id = speaker.Id,
  141. SpeakerName = speaker.SpeakerName,
  142. Qualification = speaker.Qualification,
  143. Experience = speaker.Experience,
  144. SpeakingDate = speaker.SpeakingDate,
  145. SpeakingTime = speaker.SpeakingTime,
  146. Venue = speaker.Venue,
  147. ExistingImage = speaker.ProfilePicture
  148. };
  149. if (speaker == null)
  150. {
  151. return NotFound();
  152. }
  153. return View(speakerViewModel);
  154. }
  155. [HttpPost, ActionName("Delete")]
  156. [ValidateAntiForgeryToken]
  157. public async Task<IActionResult> DeleteConfirmed(int id)
  158. {
  159. var speaker = await db.Speakers.FindAsync(id);
  160. var CurrentImage = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot\\images", speaker.ProfilePicture);
  161. db.Speakers.Remove(speaker);
  162. if (await db.SaveChangesAsync() > 0)
  163. {
  164. if (System.IO.File.Exists(CurrentImage))
  165. {
  166. System.IO.File.Delete(CurrentImage);
  167. }
  168. }
  169. return RedirectToAction(nameof(Index));
  170. }
  171. private bool SpeakerExists(int id)
  172. {
  173. return db.Speakers.Any(e => e.Id == id);
  174. }
  175. private string ProcessUploadedFile(SpeakerViewModel model)
  176. {
  177. string uniqueFileName = null;
  178. if (model.SpeakerPicture != null)
  179. {
  180. string uploadsFolder = Path.Combine(webHostEnvironment.WebRootPath, "Uploads");
  181. uniqueFileName = Guid.NewGuid().ToString() + "_" + model.SpeakerPicture.FileName;
  182. string filePath = Path.Combine(uploadsFolder, uniqueFileName);
  183. using (var fileStream = new FileStream(filePath, FileMode.Create))
  184. {
  185. model.SpeakerPicture.CopyTo(fileStream);
  186. }
  187. }
  188. return uniqueFileName;
  189. }
  190. }
  191. }
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. namespace CURDOperationWithImageUploadCore5_Demo.ViewModels
  4. {
  5. public class UploadImageViewModel
  6. {
  7. [Required]
  8. [Display(Name = "Image")]
  9. public IFormFile SpeakerPicture { get; set; }
  10. }
  11. }
EditImageViewModel
  1. namespace CURDOperationWithImageUploadCore5_Demo.ViewModels
  2. {
  3. public class EditImageViewModel : UploadImageViewModel
  4. {
  5. public int Id { get; set; }
  6. public string ExistingImage { get; set; }
  7. }
  8. }
SpeakerViewModel
  1. using System;
  2. using System.ComponentModel.DataAnnotations;
  3. namespace CURDOperationWithImageUploadCore5_Demo.ViewModels
  4. {
  5. public class SpeakerViewModel : EditImageViewModel
  6. {
  7. [Required]
  8. [Display(Name = "Name")]
  9. public string SpeakerName { get; set; }
  10. [Required]
  11. public string Qualification { get; set; }
  12. [Required]
  13. public int Experience { get; set; }
  14. [Required]
  15. [DataType(DataType.Date)]
  16. [Display(Name = "Date")]
  17. public DateTime SpeakingDate { get; set; }
  18. [Required]
  19. [DataType(DataType.Time)]
  20. [Display(Name = "Time")]
  21. public DateTime SpeakingTime { get; set; }
  22. [Required]
  23. public string Venue { get; set; }
  24. }
  25. }
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