<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: rahil merdiyev</title>
    <description>The latest articles on DEV Community by rahil merdiyev (@rahil_merdiyev_2005).</description>
    <link>https://dev.to/rahil_merdiyev_2005</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F2748955%2F9136d2f1-54f8-438d-9a22-c75cbc009763.png</url>
      <title>DEV Community: rahil merdiyev</title>
      <link>https://dev.to/rahil_merdiyev_2005</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/rahil_merdiyev_2005"/>
    <language>en</language>
    <item>
      <title>slider controller</title>
      <dc:creator>rahil merdiyev</dc:creator>
      <pubDate>Wed, 22 Jan 2025 22:29:00 +0000</pubDate>
      <link>https://dev.to/rahil_merdiyev_2005/slider-controller-3p4j</link>
      <guid>https://dev.to/rahil_merdiyev_2005/slider-controller-3p4j</guid>
      <description>&lt;p&gt;Understanding the SliderController in ASP.NET MVC&lt;br&gt;
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.&lt;/p&gt;

&lt;p&gt;Let’s walk through the code and discuss each part.&lt;/p&gt;

&lt;p&gt;Overview&lt;br&gt;
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.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Constructor&lt;br&gt;
csharp&lt;br&gt;
Copy&lt;br&gt;
public SliderController(AppDbContext context, IWebHostEnvironment env)&lt;br&gt;
{&lt;br&gt;
_context = context;&lt;br&gt;
this.env = env;&lt;br&gt;
}&lt;br&gt;
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).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;The Index Action&lt;br&gt;
csharp&lt;br&gt;
Copy&lt;br&gt;
public IActionResult Index()&lt;br&gt;
{&lt;br&gt;
List sliders = _context.Sliders.ToList();&lt;/p&gt;

&lt;p&gt;return View(sliders);&lt;br&gt;
}&lt;br&gt;
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.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The Create Actions&lt;br&gt;
csharp&lt;br&gt;
Copy&lt;br&gt;
public IActionResult Create()&lt;br&gt;
{&lt;br&gt;
return View();&lt;br&gt;
}&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;[HttpPost]&lt;br&gt;
public IActionResult Create(Slider slider)&lt;br&gt;
{&lt;br&gt;
    if (!slider.File.ContentType.Contains("image"))&lt;br&gt;
    {&lt;br&gt;
        ModelState.AddModelError("File", "Duzgun file formati daxil edin");&lt;br&gt;
    }&lt;br&gt;
    if(slider.File.Length &amp;gt; 2000000)&lt;br&gt;
    {&lt;br&gt;
        ModelState.AddModelError("File", "Sekil Max 2mb olmalidir");&lt;br&gt;
    }&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;slider.ImgUrl = slider.File.Upload(env.WebRootPath, "Upload/Slider");

if(!ModelState.IsValid)
{
    return View();
}

_context.Sliders.Add(slider);
_context.SaveChanges();
return RedirectToAction("Index");
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;}&lt;br&gt;
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.&lt;br&gt;
The second Create action is a POST request that handles form submissions. It validates the uploaded image file by checking:&lt;br&gt;
If the file is of the correct image type.&lt;br&gt;
If the image file is less than 2MB.&lt;br&gt;
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.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;The Delete Action&lt;br&gt;
csharp&lt;br&gt;
Copy&lt;br&gt;
public IActionResult Delete(int? Id)&lt;br&gt;
{&lt;br&gt;
var slider = _context.Sliders.FirstOrDefault(s =&amp;gt; s.Id == Id);&lt;br&gt;
if (slider == null)&lt;br&gt;
{&lt;br&gt;
    return NotFound();&lt;br&gt;
}&lt;br&gt;
_context.Sliders.Remove(slider);&lt;br&gt;
_context.SaveChanges();&lt;br&gt;
return RedirectToAction(nameof(Index));&lt;br&gt;
}&lt;br&gt;
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.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;The Update Actions&lt;br&gt;
csharp&lt;br&gt;
Copy&lt;br&gt;
public IActionResult Update(int? Id)&lt;br&gt;
{&lt;br&gt;
if (Id == null)&lt;br&gt;
{&lt;br&gt;
    return NotFound();&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;var slider = _context.Sliders.FirstOrDefault(s =&amp;gt; s.Id == Id);&lt;br&gt;
if (slider == null)&lt;br&gt;
{&lt;br&gt;
    return NotFound();&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;return View(slider);&lt;br&gt;
}&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;[HttpPost]&lt;br&gt;&lt;br&gt;
public IActionResult Update(Slider newslider)&lt;br&gt;
{&lt;br&gt;
    if (!ModelState.IsValid)&lt;br&gt;
    {&lt;br&gt;
        return View(newslider);&lt;br&gt;
    }&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var oldslider = _context.Sliders.FirstOrDefault(s =&amp;gt; s.Id == newslider.Id);
if (oldslider == null) 
{ 
    return NotFound(); 
}

oldslider.Id = newslider.Id;
_context.SaveChanges();

return RedirectToAction(nameof(Index)); 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;}&lt;br&gt;
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.&lt;br&gt;
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.&lt;br&gt;
Conclusion&lt;br&gt;
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.&lt;/p&gt;

&lt;p&gt;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.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[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&amp;lt;Slider&amp;gt; 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 &amp;gt; 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 =&amp;gt; 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 =&amp;gt; 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=&amp;gt; s.Id == newslider.Id);
        if (oldslider == null) { return NotFound(); }
        oldslider.Id = newslider.Id;
        _context.SaveChanges();
        return RedirectToAction(nameof(Index)); 
    }

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

</description>
    </item>
    <item>
      <title>Category Controller</title>
      <dc:creator>rahil merdiyev</dc:creator>
      <pubDate>Wed, 22 Jan 2025 22:17:36 +0000</pubDate>
      <link>https://dev.to/rahil_merdiyev_2005/category-controller-2f07</link>
      <guid>https://dev.to/rahil_merdiyev_2005/category-controller-2f07</guid>
      <description>&lt;p&gt;Certainly! Here’s a blog-style explanation of your CategoryController class in ASP.NET Core MVC, which handles operations like creating, updating, deleting, and listing categories.&lt;/p&gt;

&lt;p&gt;Building a Category Management System in ASP.NET Core MVC&lt;br&gt;
In many web applications, managing categories for products or services is a common requirement. Whether you’re building an e-commerce site, a blog, or any content-driven platform, organizing your content into categories makes it easier to navigate and manage. In this blog post, we’ll walk through the CategoryController class, which handles the creation, update, deletion, and viewing of categories within an ASP.NET Core MVC application.&lt;/p&gt;

&lt;p&gt;We will explore how to manage category data efficiently using Entity Framework Core, which allows us to interact with a database using LINQ queries, and we'll also see how to ensure proper validation and error handling along the way.&lt;/p&gt;

&lt;p&gt;Overview of the Controller&lt;br&gt;
This CategoryController class is responsible for managing the categories in the system. It allows us to:&lt;/p&gt;

&lt;p&gt;Display a list of categories&lt;br&gt;
Create new categories&lt;br&gt;
Update existing categories&lt;br&gt;
Delete categories&lt;br&gt;
Let’s break down the code and see how each action is implemented.&lt;/p&gt;

&lt;p&gt;The CategoryController Class&lt;br&gt;
Here is the complete CategoryController class:&lt;/p&gt;

&lt;p&gt;csharp&lt;br&gt;
Copy&lt;br&gt;
[Area("Manage")]&lt;br&gt;
public class CategoryController : Controller&lt;br&gt;
{&lt;br&gt;
    private readonly AppDbContext _context;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Constructor to inject the AppDbContext to interact with the database
public CategoryController(AppDbContext context)
{
    _context = context;
}

// GET: Category/Index
public async Task&amp;lt;IActionResult&amp;gt; Index()
{
    var categories = await _context.Categories.Include(p =&amp;gt; p.Products).ToListAsync();
    return View(categories);
}

// GET: Category/Create
public IActionResult Create()
{
    return View();
}

// POST: Category/Create
[HttpPost]
public IActionResult Create(Category category)
{
    if (!ModelState.IsValid)
    {
        return View(category); // Return the same view with validation errors
    }

    // Add the new category to the database
    _context.Categories.Add(category);
    _context.SaveChanges(); // Save changes to the database

    return RedirectToAction(nameof(Index)); // Redirect to the index action to display the updated category list
}

// GET: Category/Delete/5
public IActionResult Delete(int? Id)
{
    if (Id == null)
    {
        return NotFound(); // Return a 404 if the Id is not provided
    }

    var category = _context.Categories.FirstOrDefault(p =&amp;gt; p.Id == Id);
    if (category == null)
    {
        return NotFound(); // Return a 404 if the category is not found
    }

    _context.Categories.Remove(category); // Remove the category from the database
    _context.SaveChanges(); // Save changes to the database

    return RedirectToAction(nameof(Index)); // Redirect to the index action to display the updated category list
}

// GET: Category/Update/5
public IActionResult Update(int? Id)
{
    if (Id == null)
    {
        return NotFound(); // Return a 404 if the Id is not provided
    }

    var category = _context.Categories.FirstOrDefault(p =&amp;gt; p.Id == Id);
    if (category == null)
    {
        return NotFound(); // Return a 404 if the category is not found
    }

    return View(category); // Return the category to the view for editing
}

// POST: Category/Update/5
[HttpPost]
public IActionResult Update(Category newCategory)
{
    if (!ModelState.IsValid)
    {
        return View(newCategory); // Return the same view with validation errors
    }

    var oldCategory = _context.Categories.FirstOrDefault(p =&amp;gt; p.Id == newCategory.Id);
    if (oldCategory == null)
    {
        return NotFound(); // Return a 404 if the category to be updated is not found
    }

    oldCategory.Name = newCategory.Name; // Update the category name with the new value
    _context.SaveChanges(); // Save changes to the database

    return RedirectToAction(nameof(Index)); // Redirect to the index action to display the updated category list
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;}&lt;br&gt;
Breaking Down the Actions&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Index: Displaying a List of Categories
The Index action is used to display all the categories in the system. We use Entity Framework Core's Include method to load related data — in this case, we’re also including any associated Products for each category.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;csharp&lt;br&gt;
Copy&lt;br&gt;
public async Task Index()&lt;br&gt;
{&lt;br&gt;
    var categories = await _context.Categories.Include(p =&amp;gt; p.Products).ToListAsync();&lt;br&gt;
    return View(categories);&lt;br&gt;
}&lt;br&gt;
Include(p =&amp;gt; p.Products): This eagerly loads the related Products for each category.&lt;br&gt;
ToListAsync(): Executes the query asynchronously, returning a list of categories.&lt;br&gt;
The categories are then passed to the view for display.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Create: Adding a New Category
The Create action is used for creating a new category. The action has two parts:&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;GET Action (Create): Displays the form for creating a new category.&lt;br&gt;
POST Action (Create): Accepts the posted form data, validates it, and saves the new category to the database.&lt;br&gt;
GET: Show the Create Form&lt;br&gt;
csharp&lt;br&gt;
Copy&lt;br&gt;
public IActionResult Create()&lt;br&gt;
{&lt;br&gt;
    return View();&lt;br&gt;
}&lt;br&gt;
This simply returns an empty form view.&lt;/p&gt;

&lt;p&gt;POST: Handle the Form Submission&lt;br&gt;
csharp&lt;br&gt;
Copy&lt;br&gt;
[HttpPost]&lt;br&gt;
public IActionResult Create(Category category)&lt;br&gt;
{&lt;br&gt;
    if (!ModelState.IsValid)&lt;br&gt;
    {&lt;br&gt;
        return View(category); // If the model is invalid, return the form with validation errors&lt;br&gt;
    }&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;_context.Categories.Add(category); // Add the new category to the database
_context.SaveChanges(); // Save the changes to the database

return RedirectToAction(nameof(Index)); // Redirect to the Index action to display the updated list of categories
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;}&lt;br&gt;
If the model is not valid (e.g., required fields are missing), we return the form view again, displaying validation errors.&lt;br&gt;
If the model is valid, the category is added to the database, and changes are saved.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Delete: Removing a Category
The Delete action is responsible for removing a category from the system.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;GET: Show Delete Confirmation&lt;br&gt;
csharp&lt;br&gt;
Copy&lt;br&gt;
public IActionResult Delete(int? Id)&lt;br&gt;
{&lt;br&gt;
    if (Id == null)&lt;br&gt;
    {&lt;br&gt;
        return NotFound(); // If the ID is null, return a 404&lt;br&gt;
    }&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var category = _context.Categories.FirstOrDefault(p =&amp;gt; p.Id == Id);
if (category == null)
{
    return NotFound(); // If the category is not found, return a 404
}

_context.Categories.Remove(category); // Remove the category from the database
_context.SaveChanges(); // Save changes to the database

return RedirectToAction(nameof(Index)); // Redirect to the Index action to show the updated category list
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;}&lt;br&gt;
If the category is not found, it returns a 404 response.&lt;br&gt;
If found, the category is removed from the database and changes are saved.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Update: Editing a Category
The Update action allows editing an existing category.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;GET: Show the Update Form&lt;br&gt;
csharp&lt;br&gt;
Copy&lt;br&gt;
public IActionResult Update(int? Id)&lt;br&gt;
{&lt;br&gt;
    if (Id == null)&lt;br&gt;
    {&lt;br&gt;
        return NotFound(); // If the ID is null, return a 404&lt;br&gt;
    }&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var category = _context.Categories.FirstOrDefault(p =&amp;gt; p.Id == Id);
if (category == null)
{
    return NotFound(); // If the category is not found, return a 404
}

return View(category); // Return the category data to the view for editing
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;}&lt;br&gt;
POST: Handle the Update Form Submission&lt;br&gt;
csharp&lt;br&gt;
Copy&lt;br&gt;
[HttpPost]&lt;br&gt;
public IActionResult Update(Category newCategory)&lt;br&gt;
{&lt;br&gt;
    if (!ModelState.IsValid)&lt;br&gt;
    {&lt;br&gt;
        return View(newCategory); // Return the form with validation errors&lt;br&gt;
    }&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var oldCategory = _context.Categories.FirstOrDefault(p =&amp;gt; p.Id == newCategory.Id);
if (oldCategory == null)
{
    return NotFound(); // If the category is not found, return a 404
}

oldCategory.Name = newCategory.Name; // Update the category name
_context.SaveChanges(); // Save changes to the database

return RedirectToAction(nameof(Index)); // Redirect to the Index action
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;}&lt;br&gt;
Similar to the Create action, we validate the model, then update the existing category in the database.&lt;br&gt;
Conclusion&lt;br&gt;
In this post, we’ve built a simple but effective CategoryController in an ASP.NET Core MVC application, which handles the most common CRUD (Create, Read, Update, Delete) operations for categories. By using Entity Framework Core and model binding, we can easily interact with our database, validate data, and provide a responsive user experience.&lt;/p&gt;

&lt;p&gt;This setup can be easily extended to include more complex features, such as category hierarchies, custom sorting, and pagination, depending on the requirements of your application.&lt;/p&gt;

&lt;p&gt;Happy coding!&lt;/p&gt;

&lt;p&gt;Certainly! Here’s a blog-style explanation of your CategoryController class in ASP.NET Core MVC, which handles operations like creating, updating, deleting, and listing categories.&lt;/p&gt;

&lt;p&gt;Building a Category Management System in ASP.NET Core MVC&lt;br&gt;
In many web applications, managing categories for products or services is a common requirement. Whether you’re building an e-commerce site, a blog, or any content-driven platform, organizing your content into categories makes it easier to navigate and manage. In this blog post, we’ll walk through the CategoryController class, which handles the creation, update, deletion, and viewing of categories within an ASP.NET Core MVC application.&lt;/p&gt;

&lt;p&gt;We will explore how to manage category data efficiently using Entity Framework Core, which allows us to interact with a database using LINQ queries, and we'll also see how to ensure proper validation and error handling along the way.&lt;/p&gt;

&lt;p&gt;Overview of the Controller&lt;br&gt;
This CategoryController class is responsible for managing the categories in the system. It allows us to:&lt;/p&gt;

&lt;p&gt;Display a list of categories&lt;br&gt;
Create new categories&lt;br&gt;
Update existing categories&lt;br&gt;
Delete categories&lt;br&gt;
Let’s break down the code and see how each action is implemented.&lt;/p&gt;

&lt;p&gt;The CategoryController Class&lt;br&gt;
Here is the complete CategoryController class:&lt;/p&gt;

&lt;p&gt;csharp&lt;br&gt;
Copy&lt;br&gt;
[Area("Manage")]&lt;br&gt;
public class CategoryController : Controller&lt;br&gt;
{&lt;br&gt;
    private readonly AppDbContext _context;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Constructor to inject the AppDbContext to interact with the database
public CategoryController(AppDbContext context)
{
    _context = context;
}

// GET: Category/Index
public async Task&amp;lt;IActionResult&amp;gt; Index()
{
    var categories = await _context.Categories.Include(p =&amp;gt; p.Products).ToListAsync();
    return View(categories);
}

// GET: Category/Create
public IActionResult Create()
{
    return View();
}

// POST: Category/Create
[HttpPost]
public IActionResult Create(Category category)
{
    if (!ModelState.IsValid)
    {
        return View(category); // Return the same view with validation errors
    }

    // Add the new category to the database
    _context.Categories.Add(category);
    _context.SaveChanges(); // Save changes to the database

    return RedirectToAction(nameof(Index)); // Redirect to the index action to display the updated category list
}

// GET: Category/Delete/5
public IActionResult Delete(int? Id)
{
    if (Id == null)
    {
        return NotFound(); // Return a 404 if the Id is not provided
    }

    var category = _context.Categories.FirstOrDefault(p =&amp;gt; p.Id == Id);
    if (category == null)
    {
        return NotFound(); // Return a 404 if the category is not found
    }

    _context.Categories.Remove(category); // Remove the category from the database
    _context.SaveChanges(); // Save changes to the database

    return RedirectToAction(nameof(Index)); // Redirect to the index action to display the updated category list
}

// GET: Category/Update/5
public IActionResult Update(int? Id)
{
    if (Id == null)
    {
        return NotFound(); // Return a 404 if the Id is not provided
    }

    var category = _context.Categories.FirstOrDefault(p =&amp;gt; p.Id == Id);
    if (category == null)
    {
        return NotFound(); // Return a 404 if the category is not found
    }

    return View(category); // Return the category to the view for editing
}

// POST: Category/Update/5
[HttpPost]
public IActionResult Update(Category newCategory)
{
    if (!ModelState.IsValid)
    {
        return View(newCategory); // Return the same view with validation errors
    }

    var oldCategory = _context.Categories.FirstOrDefault(p =&amp;gt; p.Id == newCategory.Id);
    if (oldCategory == null)
    {
        return NotFound(); // Return a 404 if the category to be updated is not found
    }

    oldCategory.Name = newCategory.Name; // Update the category name with the new value
    _context.SaveChanges(); // Save changes to the database

    return RedirectToAction(nameof(Index)); // Redirect to the index action to display the updated category list
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;}&lt;br&gt;
Breaking Down the Actions&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Index: Displaying a List of Categories
The Index action is used to display all the categories in the system. We use Entity Framework Core's Include method to load related data — in this case, we’re also including any associated Products for each category.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;csharp&lt;br&gt;
Copy&lt;br&gt;
public async Task Index()&lt;br&gt;
{&lt;br&gt;
    var categories = await _context.Categories.Include(p =&amp;gt; p.Products).ToListAsync();&lt;br&gt;
    return View(categories);&lt;br&gt;
}&lt;br&gt;
Include(p =&amp;gt; p.Products): This eagerly loads the related Products for each category.&lt;br&gt;
ToListAsync(): Executes the query asynchronously, returning a list of categories.&lt;br&gt;
The categories are then passed to the view for display.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Create: Adding a New Category
The Create action is used for creating a new category. The action has two parts:&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;GET Action (Create): Displays the form for creating a new category.&lt;br&gt;
POST Action (Create): Accepts the posted form data, validates it, and saves the new category to the database.&lt;br&gt;
GET: Show the Create Form&lt;br&gt;
csharp&lt;br&gt;
Copy&lt;br&gt;
public IActionResult Create()&lt;br&gt;
{&lt;br&gt;
    return View();&lt;br&gt;
}&lt;br&gt;
This simply returns an empty form view.&lt;/p&gt;

&lt;p&gt;POST: Handle the Form Submission&lt;br&gt;
csharp&lt;br&gt;
Copy&lt;br&gt;
[HttpPost]&lt;br&gt;
public IActionResult Create(Category category)&lt;br&gt;
{&lt;br&gt;
    if (!ModelState.IsValid)&lt;br&gt;
    {&lt;br&gt;
        return View(category); // If the model is invalid, return the form with validation errors&lt;br&gt;
    }&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;_context.Categories.Add(category); // Add the new category to the database
_context.SaveChanges(); // Save the changes to the database

return RedirectToAction(nameof(Index)); // Redirect to the Index action to display the updated list of categories
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;}&lt;br&gt;
If the model is not valid (e.g., required fields are missing), we return the form view again, displaying validation errors.&lt;br&gt;
If the model is valid, the category is added to the database, and changes are saved.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Delete: Removing a Category
The Delete action is responsible for removing a category from the system.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;GET: Show Delete Confirmation&lt;br&gt;
csharp&lt;br&gt;
Copy&lt;br&gt;
public IActionResult Delete(int? Id)&lt;br&gt;
{&lt;br&gt;
    if (Id == null)&lt;br&gt;
    {&lt;br&gt;
        return NotFound(); // If the ID is null, return a 404&lt;br&gt;
    }&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var category = _context.Categories.FirstOrDefault(p =&amp;gt; p.Id == Id);
if (category == null)
{
    return NotFound(); // If the category is not found, return a 404
}

_context.Categories.Remove(category); // Remove the category from the database
_context.SaveChanges(); // Save changes to the database

return RedirectToAction(nameof(Index)); // Redirect to the Index action to show the updated category list
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;}&lt;br&gt;
If the category is not found, it returns a 404 response.&lt;br&gt;
If found, the category is removed from the database and changes are saved.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Update: Editing a Category
The Update action allows editing an existing category.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;GET: Show the Update Form&lt;br&gt;
csharp&lt;br&gt;
Copy&lt;br&gt;
public IActionResult Update(int? Id)&lt;br&gt;
{&lt;br&gt;
    if (Id == null)&lt;br&gt;
    {&lt;br&gt;
        return NotFound(); // If the ID is null, return a 404&lt;br&gt;
    }&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var category = _context.Categories.FirstOrDefault(p =&amp;gt; p.Id == Id);
if (category == null)
{
    return NotFound(); // If the category is not found, return a 404
}

return View(category); // Return the category data to the view for editing
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;}&lt;br&gt;
POST: Handle the Update Form Submission&lt;br&gt;
csharp&lt;br&gt;
Copy&lt;br&gt;
[HttpPost]&lt;br&gt;
public IActionResult Update(Category newCategory)&lt;br&gt;
{&lt;br&gt;
    if (!ModelState.IsValid)&lt;br&gt;
    {&lt;br&gt;
        return View(newCategory); // Return the form with validation errors&lt;br&gt;
    }&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var oldCategory = _context.Categories.FirstOrDefault(p =&amp;gt; p.Id == newCategory.Id);
if (oldCategory == null)
{
    return NotFound(); // If the category is not found, return a 404
}

oldCategory.Name = newCategory.Name; // Update the category name
_context.SaveChanges(); // Save changes to the database

return RedirectToAction(nameof(Index)); // Redirect to the Index action
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;}&lt;br&gt;
Similar to the Create action, we validate the model, then update the existing category in the database.&lt;br&gt;
Conclusion&lt;br&gt;
In this post, we’ve built a simple but effective CategoryController in an ASP.NET Core MVC application, which handles the most common CRUD (Create, Read, Update, Delete) operations for categories. By using Entity Framework Core and model binding, we can easily interact with our database, validate data, and provide a responsive user experience.&lt;/p&gt;

&lt;p&gt;This setup can be easily extended to include more complex features, such as category hierarchies, custom sorting, and pagination, depending on the requirements of your application.&lt;/p&gt;

&lt;p&gt;Happy coding!&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[Area("Manage")]
public class CategoryController : Controller
{
    AppDbContext _context;

    public CategoryController(AppDbContext context)
    {
        _context = context;
    }

    public async Task&amp;lt;IActionResult&amp;gt; Index()
    {
        var categories = await _context.Categories.Include(p =&amp;gt; p.Products).ToListAsync();
        return View(categories);
    }
    public IActionResult Create()
    {
        return View();
    }
    [HttpPost]
    public IActionResult Create(Category category)
    {
        if (!ModelState.IsValid)
        {
            return View(category);
        }
        _context.Categories.Add(category);
        _context.SaveChanges();
        return RedirectToAction(nameof(Index));
    }
    public IActionResult Delete(int? Id)
    {
        if (Id == null) { return NotFound(); }
        var category = _context.Categories.FirstOrDefault(p =&amp;gt; p.Id == Id);
        if (category == null) { return NotFound(); }
        _context.Categories.Remove(category);
        _context.SaveChanges();
        return RedirectToAction(nameof(Index));
    }
    public IActionResult Update(int? Id)
    {
        if (Id == null) { return NotFound(); }
        var category = _context.Categories.FirstOrDefault(p =&amp;gt; p.Id == Id);
        if (category == null) { return NotFound(); }
        return View(category);

    }
    [HttpPost]
    public IActionResult Update(Category newcategory)
    {
        if (!ModelState.IsValid) { return View(newcategory); }
        var oldcategory = _context.Categories.FirstOrDefault(p =&amp;gt; p.Id == newcategory.Id);
        if (oldcategory == null) { return NotFound(); }
        oldcategory.Name = newcategory.Name;
        _context.SaveChanges();
        return RedirectToAction(nameof(Index));
    }


}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

</description>
    </item>
    <item>
      <title>Extension</title>
      <dc:creator>rahil merdiyev</dc:creator>
      <pubDate>Wed, 22 Jan 2025 22:12:04 +0000</pubDate>
      <link>https://dev.to/rahil_merdiyev_2005/extension-e06</link>
      <guid>https://dev.to/rahil_merdiyev_2005/extension-e06</guid>
      <description>&lt;p&gt;Efficient File Upload in ASP.NET Core: Using Extension Methods for IFormFile&lt;br&gt;
In modern web applications, file uploads are a frequent requirement, whether it's for profile pictures, documents, or other types of media. Handling these uploads efficiently and securely is crucial. In this post, we'll walk through a solution in ASP.NET Core that makes file uploads both easy and reliable by using extension methods.&lt;/p&gt;

&lt;p&gt;We’ll cover how to write an extension method for the IFormFile interface, which allows us to handle file uploads in a clean and reusable way. But before we dive into the code, let’s first discuss the concept of extension methods and why they’re beneficial.&lt;/p&gt;

&lt;p&gt;What Are Extension Methods?&lt;br&gt;
In C#, extension methods allow us to "add" new methods to existing types without modifying their original source code. This is particularly useful when working with built-in types or third-party libraries. In this case, we’ll extend the IFormFile interface to add a custom Upload method for file handling.&lt;/p&gt;

&lt;p&gt;The Task&lt;br&gt;
We want to upload files to the server with these requirements:&lt;/p&gt;

&lt;p&gt;File Name Handling: If the file name exceeds 64 characters, truncate it.&lt;br&gt;
Ensure Uniqueness: Every uploaded file must have a unique name to avoid overwriting existing files.&lt;br&gt;
File Storage: Save the file in a specified folder on the server.&lt;br&gt;
Return File Name: Return the new, unique file name for further processing (e.g., saving in the database).&lt;br&gt;
Let’s take a look at how we can achieve this in a few simple steps with an extension method.&lt;/p&gt;

&lt;p&gt;Code Walkthrough&lt;br&gt;
Below is the code for our extension method Upload:&lt;/p&gt;

&lt;p&gt;csharp&lt;br&gt;
Copy&lt;br&gt;
public static class FileExtension&lt;br&gt;
{&lt;br&gt;
    // Extension method for IFormFile to handle file uploads&lt;br&gt;
    public static string Upload(this IFormFile file, string rootPath, string foldername)&lt;br&gt;
    {&lt;br&gt;
        // Step 1: Extract the original file name&lt;br&gt;
        string filname = file.FileName;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    // Step 2: Truncate the file name if it is longer than 64 characters
    if (filname.Length &amp;gt; 64)
    {
        filname = filname.Substring(filname.Length - 64);
    }

    // Step 3: Generate a unique file name by appending a GUID
    filname = Guid.NewGuid() + filname;

    // Step 4: Build the complete file path (root + folder + file name)
    string path = Path.Combine(rootPath, foldername, filname);

    // Step 5: Save the file to the server at the generated path
    using (FileStream stream = new FileStream(path, FileMode.Create))
    {
        file.CopyTo(stream);
    }

    // Step 6: Return the new file name
    return filname;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;}&lt;br&gt;
Step-by-Step Explanation&lt;br&gt;
Extracting the Original File Name: The file name is obtained using file.FileName, which provides the original name of the file uploaded by the user.&lt;/p&gt;

&lt;p&gt;csharp&lt;br&gt;
Copy&lt;br&gt;
string filname = file.FileName;&lt;br&gt;
Truncating the File Name: If the file name is too long (over 64 characters), we truncate it to the last 64 characters. This is important because some file systems might have limitations on the length of file names.&lt;/p&gt;

&lt;p&gt;csharp&lt;br&gt;
Copy&lt;br&gt;
if (filname.Length &amp;gt; 64)&lt;br&gt;
{&lt;br&gt;
    filname = filname.Substring(filname.Length - 64);&lt;br&gt;
}&lt;br&gt;
Ensuring Unique File Names: To ensure that files uploaded with the same original name don’t overwrite each other, we prepend a GUID (Globally Unique Identifier) to the file name. This guarantees that every file has a unique name.&lt;/p&gt;

&lt;p&gt;csharp&lt;br&gt;
Copy&lt;br&gt;
filname = Guid.NewGuid() + filname;&lt;br&gt;
Building the Complete File Path: The rootPath (which specifies the base directory on the server), foldername (the folder where files should be stored), and filname (the new file name) are combined to create the full file path. This path tells the system where to save the uploaded file.&lt;/p&gt;

&lt;p&gt;csharp&lt;br&gt;
Copy&lt;br&gt;
string path = Path.Combine(rootPath, foldername, filname);&lt;br&gt;
Saving the File: Using a FileStream, we write the contents of the uploaded file to the server. The file.CopyTo(stream) method copies the content of the uploaded file to the file stream, which then writes it to the disk.&lt;/p&gt;

&lt;p&gt;csharp&lt;br&gt;
Copy&lt;br&gt;
using (FileStream stream = new FileStream(path, FileMode.Create))&lt;br&gt;
{&lt;br&gt;
    file.CopyTo(stream);&lt;br&gt;
}&lt;br&gt;
Here, FileMode.Create ensures that the file is created at the specified path. If the file already exists, it will be overwritten.&lt;/p&gt;

&lt;p&gt;Returning the New File Name: Finally, the method returns the new file name (filname). This new name is now unique and can be used to refer to the uploaded file, for example, when storing it in a database.&lt;/p&gt;

&lt;p&gt;csharp&lt;br&gt;
Copy&lt;br&gt;
return filname;&lt;br&gt;
Example Usage in an ASP.NET Core Controller&lt;br&gt;
Here’s how you can use the Upload method in an ASP.NET Core controller to handle file uploads:&lt;/p&gt;

&lt;p&gt;csharp&lt;br&gt;
Copy&lt;br&gt;
public class FileUploadController : Controller&lt;br&gt;
{&lt;br&gt;
    private readonly string _rootPath = "C:\UploadedFiles";&lt;br&gt;
    private readonly string _folderName = "Images";&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[HttpPost]
public IActionResult UploadFile(IFormFile file)
{
    if (file != null &amp;amp;&amp;amp; file.Length &amp;gt; 0)
    {
        // Use the Upload extension method to upload the file
        string uploadedFileName = file.Upload(_rootPath, _folderName);

        // Return a success response with the new file name
        return Ok(new { FileName = uploadedFileName });
    }

    return BadRequest("No file uploaded.");
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;}&lt;br&gt;
In this example:&lt;/p&gt;

&lt;p&gt;The UploadFile method handles a POST request with an uploaded file (IFormFile).&lt;br&gt;
The Upload method is called to upload the file to the server.&lt;br&gt;
The Ok response returns the new file name, which can be used in further processes like storing the file name in a database or displaying it on the frontend.&lt;br&gt;
Enhancements and Best Practices&lt;br&gt;
File Type Validation: You might want to restrict the types of files users can upload (e.g., only allowing image files). You can check the MIME type of the file before uploading.&lt;/p&gt;

&lt;p&gt;csharp&lt;br&gt;
Copy&lt;br&gt;
var allowedTypes = new[] { "image/jpeg", "image/png" };&lt;br&gt;
if (!allowedTypes.Contains(file.ContentType))&lt;br&gt;
{&lt;br&gt;
    return BadRequest("Invalid file type.");&lt;br&gt;
}&lt;br&gt;
File Size Validation: It's a good idea to limit the size of files that can be uploaded to prevent users from uploading very large files.&lt;/p&gt;

&lt;p&gt;csharp&lt;br&gt;
Copy&lt;br&gt;
if (file.Length &amp;gt; 10 * 1024 * 1024)  // Limit file size to 10 MB&lt;br&gt;
{&lt;br&gt;
    return BadRequest("File size exceeds the maximum allowed size.");&lt;br&gt;
}&lt;br&gt;
Directory Existence Check: Make sure the target folder exists before attempting to save the file. If it doesn't, create it:&lt;/p&gt;

&lt;p&gt;csharp&lt;br&gt;
Copy&lt;br&gt;
string folderPath = Path.Combine(rootPath, foldername);&lt;br&gt;
if (!Directory.Exists(folderPath))&lt;br&gt;
{&lt;br&gt;
    Directory.CreateDirectory(folderPath);&lt;br&gt;
}&lt;br&gt;
Error Handling: It’s essential to handle errors such as file write permissions, insufficient disk space, or other file-related issues. Wrap the file upload process in a try-catch block to handle exceptions gracefully.&lt;/p&gt;

&lt;p&gt;Conclusion&lt;br&gt;
Using extension methods in C# can help make file handling much more convenient and reusable. In this blog post, we’ve demonstrated how to create an extension method for IFormFile to upload files efficiently while ensuring that the file names are unique and properly handled. By following these best practices and incorporating additional validations, you can build a robust file upload system for your ASP.NET Core applications.&lt;/p&gt;

&lt;p&gt;Happy coding!&lt;/p&gt;

&lt;p&gt;This blog post provides a detailed guide on how to implement and use the Upload method while following best practices. It also highlights potential areas for improvement, such as file validation and error handling, ensuring that your file upload system is secure and efficient.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public static class FileExtension
{
    public static string Upload(this IFormFile file,string rootPath,string foldername)
    {
        string filname =file.FileName;
        if(filname.Length &amp;gt; 64)
        {
            filname = filname.Substring(filname.Length - 64);
        } 
        filname= Guid.NewGuid() + filname;
        string path = Path.Combine(rootPath,foldername,filname);
        using (FileStream stream = new FileStream(path, FileMode.Create))
        {
            file.CopyTo(stream);
        }
        return filname;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

</description>
    </item>
  </channel>
</rss>
