Understanding the SliderController in ASP.NET MVC
In this blog, we will explore the SliderController in an ASP.NET MVC application, breaking down the various actions and logic used to manage slider data in the system. The controller provides basic CRUD (Create, Read, Update, Delete) functionality for managing image sliders, typically used in the admin area of a website to manage images displayed on the homepage or other sections.
Let’s walk through the code and discuss each part.
Overview
The SliderController is part of the Manage area in the application. It handles the interaction between the user and the slider data in the database. It uses an AppDbContext to access the database and an IWebHostEnvironment to interact with the file system for saving images.
- Constructor
csharp
Copy
public SliderController(AppDbContext context, IWebHostEnvironment env)
{
_context = context;
this.env = env;
}
In the constructor, two dependencies are injected into the controller: AppDbContext for database operations and IWebHostEnvironment for file system interactions. This allows the controller to interact with both the database (to fetch, add, delete, or update slider records) and the local file system (to upload images). - The Index Action
csharp
Copy
public IActionResult Index()
{
List sliders = _context.Sliders.ToList();return View(sliders);
}
The Index action fetches all the Slider records from the database and passes them to the view for display. This is typically used to show a list of sliders that have already been uploaded or created in the system. - The Create Actions
csharp
Copy
public IActionResult Create()
{
return View();
}
[HttpPost]
public IActionResult Create(Slider slider)
{
if (!slider.File.ContentType.Contains("image"))
{
ModelState.AddModelError("File", "Duzgun file formati daxil edin");
}
if(slider.File.Length > 2000000)
{
ModelState.AddModelError("File", "Sekil Max 2mb olmalidir");
}
slider.ImgUrl = slider.File.Upload(env.WebRootPath, "Upload/Slider");
if(!ModelState.IsValid)
{
return View();
}
_context.Sliders.Add(slider);
_context.SaveChanges();
return RedirectToAction("Index");
}
The first Create action is a simple GET request that returns the view for creating a new slider. It doesn’t take any parameters and simply renders the form for creating a new slider.
The second Create action is a POST request that handles form submissions. It validates the uploaded image file by checking:
If the file is of the correct image type.
If the image file is less than 2MB.
If either of these conditions fails, an error is added to the ModelState, and the form is redisplayed to the user. If validation passes, the image is uploaded to a specific directory, and a new Slider object is saved to the database. Finally, the user is redirected to the Index action to view the updated list of sliders.
- The Delete Action
csharp
Copy
public IActionResult Delete(int? Id)
{
var slider = _context.Sliders.FirstOrDefault(s => s.Id == Id);
if (slider == null)
{
return NotFound();
}
_context.Sliders.Remove(slider);
_context.SaveChanges();
return RedirectToAction(nameof(Index));
}
The Delete action handles the deletion of a slider. It first checks if a Slider with the given Id exists in the database. If not, it returns a NotFound() result. If the slider is found, it is removed from the context, and the changes are saved. Afterward, the user is redirected back to the Index action to view the updated list of sliders. - The Update Actions
csharp
Copy
public IActionResult Update(int? Id)
{
if (Id == null)
{
return NotFound();
}var slider = _context.Sliders.FirstOrDefault(s => s.Id == Id);
if (slider == null)
{
return NotFound();
}return View(slider);
}
[HttpPost]
public IActionResult Update(Slider newslider)
{
if (!ModelState.IsValid)
{
return View(newslider);
}
var oldslider = _context.Sliders.FirstOrDefault(s => s.Id == newslider.Id);
if (oldslider == null)
{
return NotFound();
}
oldslider.Id = newslider.Id;
_context.SaveChanges();
return RedirectToAction(nameof(Index));
}
The first Update action is a GET request. It accepts an Id parameter, finds the corresponding Slider from the database, and passes it to the view for editing.
The second Update action is a POST request that updates the Slider record in the database. If the ModelState is valid, it retrieves the existing slider from the database and updates its properties with the new values from the form. After saving the changes, the user is redirected to the Index action.
Conclusion
This SliderController is a great example of how to implement CRUD operations in an ASP.NET MVC application, including file uploads and validation. The Create, Update, and Delete actions provide a straightforward way to manage the slider images, while the Index action displays them in a list for the user.
By adhering to common patterns such as dependency injection, model validation, and redirecting after data changes, this controller provides a clear, maintainable approach to managing data in an MVC application.
[Area("Manage")]
public class SliderController : Controller
{
AppDbContext _context;
private readonly IWebHostEnvironment env;
public SliderController(AppDbContext context, IWebHostEnvironment env)
{
_context = context;
this.env = env;
}
public IActionResult Index()
{
List<Slider> sliders = _context.Sliders.ToList();
return View(sliders);
}
public IActionResult Create()
{
return View();
}
[HttpPost]
public IActionResult Create(Slider slider)
{
if (!slider.File.ContentType.Contains("image"))
{
ModelState.AddModelError("File", "Duzgun file formati daxil edin");
}
if(slider.File.Length > 2000000)
{
ModelState.AddModelError("File", "Sekil Max 2mb olmalidir");
}
slider.ImgUrl = slider.File.Upload(env.WebRootPath, "Upload/Slider");
if(!ModelState.IsValid)
{
return View();
}
_context.Sliders.Add(slider);
_context.SaveChanges();
return RedirectToAction("Index");
}
public IActionResult Delete(int? Id)
{
var slider = _context.Sliders.FirstOrDefault(s => s.Id == Id);
if (slider == null)
{
return NotFound();
}
_context.Sliders.Remove(slider);
_context.SaveChanges();
return RedirectToAction(nameof(Index));
}
public IActionResult Update(int? Id)
{
if (Id == null)
{
return NotFound();
}
var slider = _context.Sliders.FirstOrDefault(s => s.Id == Id);
if (slider == null)
{
return NotFound();
}
return View(slider);
}
[HttpPost]
public IActionResult Update(Slider newslider)
{
if (!ModelState.IsValid)
{
return View(newslider);
}
var oldslider= _context.Sliders.FirstOrDefault(s=> s.Id == newslider.Id);
if (oldslider == null) { return NotFound(); }
oldslider.Id = newslider.Id;
_context.SaveChanges();
return RedirectToAction(nameof(Index));
}
}
Author Of article : rahil merdiyev Read full article