Advertisement

Advertisement

How to Create asp.net core mvc CRUD upload image app using db 1st approach

 How to Create asp.net core mvc CRUD upload image app using db 1st approach

Step 1: Create the Database

  1. Open SQL Server and create a new database (e.g., ImageCRUDDB).
  2. Create a table to store image details:
CREATE TABLE Product(
    Id INT PRIMARY KEY IDENTITY(1,1),
    NameNVARCHAR(100) NOT NULL,
    Price INT,
    ImagePath NVARCHAR(MAX),
);

Step 2: Set Up Your Project

  1. Create a new ASP.NET Core MVC project in Visual Studio.
  2. Add a folder named wwwroot/images for storing uploaded images.

Step 3: Scaffold the Database Context

  1. Add the NuGet package for Entity Framework Core tools:
    Install-Package Microsoft.EntityFrameworkCore.SqlServer Install-Package Microsoft.EntityFrameworkCore.Tools
     2. Scaffold the database to generate the model and context:

Scaffold-DbContext "Server=YourServerName;Database=ImageCRUDDB;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

After getting the auto-generated DbContext file delete the warning message(connection string) .

Step 4:  Add connection string in appsetting.json file 

,
    "ConnectionStrings": {
        "DefaultConnection": "Server = DESKTOP-9M9EDAA\\SQLEXPRESS; Database = imageDb; Trusted_Connection = True; MultipleActiveResultSets = True; TrustServerCertificate = True;"
    }

Step 5:  Add service in program.cs file 

builder.Services.AddDbContext<ImageDbContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));

Step 6: Add Product.cs and ProductVM.cs model in model folder

Product.cs

public partial class Product
{
    public int Id { get; set; }
    [Required]
    public string Name { get; set; } = null!;
    [Required]
    public int Price { get; set; }
    [Required]
    public string ImagePath { get; set; } = null!;
}

ProductVM.cs

public partial class Product
{
    public int Id { get; set; }
    [Required]
    public string Name { get; set; } = null!;
    [Required]
    public int Price { get; set; }
    [Required]
     public IFormFile Photo { get; set; } = null!;
}

Step 7:  Add ProductController.cs

public class ProductController : Controller
{
    ImageDbContext _db;
    IWebHostEnvironment _env;
    public ProductController(ImageDbContext db, IWebHostEnvironment env)
    {
        _db = db;
        _env = env;
    }
    public IActionResult Index()
    {
        return View(_db.Products.ToList());
    } 
    public IActionResult AddProduct()
    {
        return View();
    }
    [HttpPost]
    public IActionResult  AddProduct(ProductVM prod)
    {
        string fileName = "";
        if (prod.Photo != null)
        {
            string folder = Path.Combine(_env.WebRootPath, "images");
            fileName = Guid.NewGuid().ToString() + "" + prod.Photo.FileName;
            string filePath = Path.Combine(folder, fileName);
            prod.Photo.CopyTo(new FileStream(filePath, FileMode.Create));

            Product p = new Product()
            {
                Name = prod.Name,
                Price = prod.Price,
                ImagePath = fileName
            };
            _db.Products.Add(p);
            _db.SaveChanges();
            TempData["Success"] = "Product Added Successfully!";
            return RedirectToAction("Index");
        }
        return View();
    }
// GET: Products/Edit/5
public async Task<IActionResult> Edit(int? id)
{
    if (id == null)
    {
        return NotFound();
    }

    var image = await _context.Products.FindAsync(id);
    if (image == null)
    {
        return NotFound();
    }

    return View(image);
}
// POST: Products/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, [Bind("Id,Name, Price,ImagePath")] Product prod, IFormFile newImage)
{
    if (id != prod.Id)
    {
        return NotFound();
    }

    if (ModelState.IsValid)
    {
        try
        {
            var existingImage = await _context.Products.FindAsync(id);

            if (existingImage == null)
            {
                return NotFound();
            }

            // Update Name
            existingImage.Name= image.Name;

            // Handle new image upload
            if (newImage != null)
            {
                string uploadsFolder = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/images");
                string uniqueFileName = Guid.NewGuid().ToString() + "_" + newImage.FileName;
                string filePath = Path.Combine(uploadsFolder, uniqueFileName);

                // Save new file
                using (var fileStream = new FileStream(filePath, FileMode.Create))
                {
                    await newImage.CopyToAsync(fileStream);
                }

                // Delete old file if exists
                if (!string.IsNullOrEmpty(existingImage.ImagePath))
                {
                    string oldFilePath = Path.Combine(uploadsFolder, existingImage.ImagePath);
                    if (System.IO.File.Exists(oldFilePath))
                    {
                        System.IO.File.Delete(oldFilePath);
                    }
                }

                // Update database with new image path
                existingImage.ImagePath = uniqueFileName;
            }

            _context.Update(existingImage);
            await _context.SaveChangesAsync();
        }
        catch (DbUpdateConcurrencyException)
        {
            if (!ImageExists(image.Id))
            {
                return NotFound();
            }
            else
            {
                throw;
            }
        }

        return RedirectToAction(nameof(Index));
    }
    return View(image);
}

private bool ImageExists(int id)
{
    return _context.Images.Any(e => e.Id == id);
}
// GET: Products/Details/5
public async Task<IActionResult> Details(int? id)
{
    if (id == null)
    {
        return NotFound();
    }

    var image = await _context.Products
        .FirstOrDefaultAsync(m => m.Id == id);
    if (image == null)
    {
        return NotFound();
    }

    return View(image);
}


}

Step : 8 Add view 

Index.cshtml

@model IEnumerable<ImageUpload.models.Product>

@{
    ViewData["Title"] = "Index";
}

<h1>Index</h1>

<p>
    <a asp-action="Create">Create New</a>
</p>
<p style="color:green">
    @TempData["Success"]
</p>
<table class="table">
    <thead>
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.Name)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Price)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.ImagePath)
            </th>
            <th></th>
        </tr>
    </thead>
    <tbody>
@foreach (var item in Model) {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.Name)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Price)
            </td>
            <td>
                    <img src="~/images/@Html.DisplayFor(modelItem => item.ImagePath)" style="width:100px; height:100px;" />
            </td>
            <td>
                <a asp-action="Edit" asp-route-id="@item.Id">Edit</a> |
                <a asp-action="Details" asp-route-id="@item.Id">Details</a> |
                <a asp-action="Delete" asp-route-id="@item.Id">Delete</a>
            </td>
        </tr>
}
    </tbody>
</table>

AddProduct.cshtml

@model ImageUpload.models.ProductVM

@{
    ViewData["Title"] = "AddProduct";
}

<h1>AddProduct</h1>

<h4>Product</h4>
<hr />
<div class="row">
    <div class="col-md-4">
        <form asp-action="AddProduct" enctype="multipart/form-data" >
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="Name" class="control-label"></label>
                <input asp-for="Name" class="form-control" />
                <span asp-validation-for="Name" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Price" class="control-label"></label>
                <input asp-for="Price" class="form-control" />
                <span asp-validation-for="Price" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Photo" class="control-label"></label>
                <input asp-for="Photo" class="form-control" />
                <span asp-validation-for="Photo" class="text-danger"></span>
            </div>
            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-primary" />
            </div>
        </form>
    </div>
</div>

<div>
    <a asp-action="Index">Back to List</a>
</div>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

Edit.cshtml

@model ImageCRUDApp.Models.Image

@{
    ViewData["Title"] = "Edit Image";
}

<h1>Edit Image</h1>

<div class="row">
    <div class="col-md-6">
        <form asp-action="Edit" enctype="multipart/form-data">
            <input type="hidden" asp-for="Id" />
            <div class="form-group">
                <label asp-for="Title" class="control-label"></label>
                <input asp-for="Title" class="form-control" />
                <span asp-validation-for="Title" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label>Current Image</label><br />
                @if (!string.IsNullOrEmpty(Model.ImagePath))
                {
                    <img src="~/images/@Model.ImagePath" alt="@Model.Title" width="100" height="100" />
                }
                else
                {
                    <p>No image uploaded</p>
                }
            </div>
            <div class="form-group">
                <label asp-for="ImagePath">Upload New Image</label>
                <input type="file" name="newImage" class="form-control" />
            </div>
            <div class="form-group">
                <input type="submit" value="Save" class="btn btn-primary" />
                <a asp-action="Index" class="btn btn-secondary">Back to List</a>
            </div>
        </form>
    </div>
</div>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

Details.cshtml

@model ImageCRUDApp.Models.Image

@{
    ViewData["Title"] = "Product Details";
}

<h1>Image Details</h1>

<div>
    <h4>Image</h4>
    <hr />
    <dl class="row">
        <dt class="col-sm-2">Name</dt>
        <dd class="col-sm-10">@Model.Name</dd>
        <dt class="col-sm-2">Price</dt>
        <dd class="col-sm-10">
            @if (!string.IsNullOrEmpty(Model.ImagePath))
            {
                <img src="~/images/@Model.ImagePath" alt="@Model.Name" width="300" />
            }
            else
            {
                <p>No image available</p>
            }
        </dd>
        <dt class="col-sm-2">Upload Date</dt>
        <dd class="col-sm-10">@Model.UploadDate</dd>
    </dl>
</div>
<div>
    <a asp-action="Edit" asp-route-id="@Model.Id" class="btn btn-primary">Edit</a>
    <a asp-action="Index" class="btn btn-secondary">Back to List</a>
</div>





How to Create asp.net core mvc CRUD upload image app using db 1st approach How to Create asp.net core mvc CRUD upload image app using db 1st approach Reviewed by Rikesh on December 07, 2024 Rating: 5

No comments:

Powered by Blogger.