Skip to content

Edit not working properly, based on my selected item it is display different one. #13

@kk-call

Description

@kk-call

--------index.cshtml----------------------

Product List

ll   create new Product
    </div>
</div>
<br />

<h1>CoverType</h1>
<div class="row">
    <div class="col-10">
        <table id="tblData" class="table  table-bordered table-striped" style="width:100%">
            <thead>

                <tr>

                    <th>Title</th>

                    <th>ISBN</th>

                    <th>Price</th>

                    <th>Cateogry</th>

                    <th>CoverType</th>

                    
                    <th> button</th>
                </tr>
            </thead>
            @* <tbody>
            @foreach (var Obj in Model)
            {
            <tr>
            <td width="50px">
            @Obj.NameC
            </td>

            <td>
            <div class="w-75 btn-group" role="group">
            <a asp-controller="CoverType" asp-action="Edit" asp-route-id="@Obj.IdC" class="btn btn-primary mx-2"><i class="bi bi-pencil-square"></i>Edit</a>

            <a asp-controller="CoverType" asp-action="Delete" asp-route-id="@Obj.IdC" class="btn btn-primary mx-2"><i class="bi bi-trash3"></i>Delete</a>
            </div>

            </td>
            </tr>
            }
            </tbody>*@

        </table>
    </div>

    <div class="col-2">
        
      @*      <div class="col-2 p-4">
                <img src="@Model.Product.ImgUrl" width="100%"
                     style="border-radius:5px; border:1px solid #bbb9b9" />*@
        
    </div>
    </div>

@section Scripts
{
<script src="~/js/Product.js"></script>
}
=============================upsert.cshtml========================
@model BulkyBook.Models.ViewModel.ProductVM

<div class="row">

    <div class="col-10">
        <div class=" border p-4 p-3 row">
            <div class="col-12 pb-2">
                <h2 class="text-primary"> @(Model.Product.id != 0 ? "Update" : "Create") Product</h2>
            </div>
            @* Summerize the error message ..*@
            @*<div asp-validation-summary="All"></div>*@
            <div class="mb-3">
                <label asp-for="Product.Title"></label>
                <input asp-for="Product.Title" class="form-control" />
                <span asp-validation-for="Product.Title" class="text-danger"></span>
            </div>
            <div class="mb-3">
                <label asp-for="Product.Description"></label>
                <textarea asp-for="Product.Description" rows="3" class="form-control"></textarea>
                <span asp-validation-for="Product.Description" class="text-danger"></span>
            </div>
            <div class="mb-3 col-6">
                <label asp-for="Product.ISBN"></label>
                <input asp-for="Product.ISBN" class="form-control" />
                <span asp-validation-for="Product.ISBN" class="text-danger"></span>
            </div>
            <div class="mb-3 col-6">
                <label asp-for="Product.Author"></label>
                <input asp-for="Product.Author" class="form-control" />
                <span asp-validation-for="Product.Author" class="text-danger"></span>
            </div>
            <div class="mb-3 col-6">
                <label asp-for="Product.Price"></label>
                <input asp-for="Product.Price" class="form-control" />
                <span asp-validation-for="Product.Price" class="text-danger"></span>
            </div>
            <div class="mb-3 col-6">
                <label asp-for="Product.Price50"></label>
                <input asp-for="Product.Price50" class="form-control" />
                <span asp-validation-for="Product.Price50" class="text-danger"></span>
            </div>
            <div class="mb-3 col-6">
                <label asp-for="Product.Price100"></label>
                <input asp-for="Product.Price100" class="form-control" />
                <span asp-validation-for="Product.Price100" class="text-danger"></span>
            </div>
            <div class="mb-3 col-6">
                <label asp-for="Product.ListPrice"></label>
                <input asp-for="Product.ListPrice" class="form-control" />
                <span asp-validation-for="Product.ListPrice" class="text-danger"></span>
            </div>
            <div class="mb-3">
                <label asp-for="Product.ImgUrl"></label>
                <input type="file" id="uploadBox" name="file" class="form-control" />

            </div>
            <div class="mb-3  col-6">
                <label asp-for="Product.categoryId"></label>
                <select asp-for="Product.categoryId" asp-items="@Model.categoryList" class="form-control">
                    <option disabled selected>--Select--</option>
                </select>
                <span asp-validation-for="Product.categoryId" class="text-danger"></span>
            </div>
            <div class="mb-3  col-6">
                <label asp-for="Product.CoverTypeId"></label>
                <select asp-for="Product.CoverTypeId" asp-items="@Model.CoverTypeList" class="form-control">
                    <option disabled selected>--Select--</option>
                </select>
                <span asp-validation-for="Product.CoverTypeId" class="text-danger"></span>
            </div>
            <div class="col-12">

                @if (Model.Product.id != 0)
                {
                    <button type="submit" class="btn btn-primary" style="width:150px">Update</button>
                }
                else
                {
                    <button type="submit" onclick="return Validateinput()" class="btn btn-primary" style="width:150px">Create</button>
                }

                <a asp-controller="Product" asp-action="index">
                    Back to the List
                </a>
            </div>
        </div>
    </div>
   
    <div class="col-2 p-8">
        <img src="@Model.Product.ImgUrl" width="100%"
         style="border-radius:5px; border:1px solid #bbb9b9"/>

       @* <img src="~/images/products/@Html.DisplayFor(model =>model.Product.ImgUrl)" style="height:200px;width:200px;" />*@
        @*<img src="/images/products/16056dd8-e098-49d3-8030-161f3ac9120c.jpg" width="100%"
             style="border-radius:5px; border:1px solid #bbb9b9" />*@
    </div>

</div>

@section Scripts{
@{

}
<script>
function Validateinput()
{
if(document.getElementById("uploadBox").value=="")
{
swal({

                text: "please upload the image!",
                icon: "error",
                button: "Aww yiss!",
            });
            return false;
        }
        else
        {
            return true;
        }
    }
</script>
}

============================productcontroller==================================
using Bulkybook.DataAccess.Repository;
using Bulkybook.DataAccess.Repository.IRepository;
using BulkyBook.DataAccess;
using BulkyBook.Models;
using BulkyBook.Models.ViewModel;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.DotNet.Scaffolding.Shared.Messaging;
using Microsoft.EntityFrameworkCore;

namespace BulkybookWeb.Areas.Admin.Controllers
{
public class ProductController : Controller
{

    private readonly IUnitofWork _UnitofWork;
    private readonly  IWebHostEnvironment _hostEnvironment;


    public ProductController(IUnitofWork unitofWork, IWebHostEnvironment hostEnvironment)
    {
        _UnitofWork = unitofWork;
        _hostEnvironment = hostEnvironment; 
    }
    public IActionResult Index()
    {
        //removed the list and Enu
        //var categories= _DBcontext.categories.ToList();

        //IEnumerable<CoverType> objCoverType = _UnitofWork.CoverType.GetAll();
        //return View(objCoverType);

        //var products = _UnitofWork.Product.GetAll(includeproperties: "Category,CoverType");

        return View();
    }


    //===========================================Edit=================================================//
    public IActionResult Upsert(int? id)
    {
        ProductVM productVM = new()
        {
            Product = new(),

                categoryList = _UnitofWork.Category.GetAll().Select(i => new SelectListItem
                {
                    Text = i.Name,
                    Value = i.Id.ToString()
                }),

            CoverTypeList = _UnitofWork.CoverType.GetAll().Select(i => new SelectListItem
            {
                Text = i.NameC,
                Value = i.IdC.ToString()
            }),

        };

        
        // V.1===> ...
        // this below code used for ViewBag and Viewdata...//
        //we are using viewModel instead of viewbage and ViewModel//
        //so this below code commented//
        //     IEnumerable<SelectListItem> categoryList = _UnitofWork.Category.GetAll().Select(
        //    u => new SelectListItem
        //    {
        //        Text = u.Name,
        //        Value = u.Id.ToString()
        //    }
        //); ;

        //    IEnumerable<SelectListItem> CoverTypeList = _UnitofWork.CoverType.GetAll().Select(
        //       u => new SelectListItem
        //       {
        //           Text = u.NameC,
        //           Value = u.IdC.ToString()
        //       }

        //   ); ;

        // V.1<=== ...
        if (id == 0 || id == null)
        {
            
            //create the product
            // V.1===> ...
            //ViewBag.categorylist=categoryList;
            //ViewData["CoverTypeList"] = CoverTypeList;
            //V.1 <===
            return View(productVM);
        }
        else
        {

            //Update the product
            productVM.Product=_UnitofWork.Product.GetFirstOrDefault(u=>u.id == id);   
            return View(productVM);
        }

      
    }

    //post
    [HttpPost]
    //eliminating cross request(unwanted request)
    [ValidateAntiForgeryToken]
    public IActionResult Upsert(ProductVM Obj,IFormFile file)
    {
        if (ModelState.IsValid)
        {
            string wwwRootPath = _hostEnvironment.WebRootPath;
            if(file!=null)
            {
                string filename=Guid.NewGuid().ToString();  
                var uploads=Path.Combine(wwwRootPath, @"images\ProductImg\");
                var extension = Path.GetExtension(file.FileName);

                //old need to remove before updating check that logic//
                if(Obj.Product.ImgUrl!=null)
                {
                    var oldpath = Path.Combine(wwwRootPath, Obj.Product.ImgUrl.TrimStart('\\'));
                    if(System.IO.File.Exists(oldpath))
                    {
                        System.IO.File.Delete(oldpath);
                    }
                }

                using (var filestream = new FileStream(Path.Combine(uploads, filename + extension), FileMode.Create))
                {
                    file.CopyTo(filestream);
                }
                Obj.Product.ImgUrl= @"images\ProductImg\" + filename + extension;
            }
            if(Obj.Product.id==0)
            {
               _UnitofWork.Product.Add(Obj.Product);
            }
            else
            {
                _UnitofWork.Product.update(Obj.Product);
            }
          
            _UnitofWork.save();
            TempData["success"] = "The product created SuccessFully";
            return RedirectToAction("index");
        }
        return View(Obj.Product);

    }


    //===========================================Delete=================================================//
    //public IActionResult Delete(int? id)
    //{
    //    if (id == 0 || id == null)
    //    {
    //        return NotFound();
    //    }
     
    //    var CoverTypefromdefult = _UnitofWork.CoverType.GetFirstOrDefault(u => u.IdC == id);
    
    //    if (CoverTypefromdefult == null)
    //    {
    //        return NotFound();
    //    }
    //    return View(CoverTypefromdefult);
    //}

   
    #region API CALLS
    [HttpGet]
    public IActionResult GetAll()
    {
        var ProductList = _UnitofWork.Product.GetAll(includeproperties: "Category,CoverType");
        return Json(new { data = ProductList });
    }


    //post

    //Eliminating cross request(unwanted request)
    
    [HttpDelete]
    public IActionResult Delete(int? id)
    {
        var obj = _UnitofWork.Product.GetFirstOrDefault(u => u.id == id);
        if (obj == null)
        {
            return Json(new {success=false,Message="Error while Deleting"});   
        }

        var oldpath = Path.Combine(_hostEnvironment.WebRootPath,obj.ImgUrl.TrimStart('\\'));
        if (System.IO.File.Exists(oldpath))
        {
            System.IO.File.Delete(oldpath);
        }
        _UnitofWork.Product.Remove(obj);
        _UnitofWork.save();       
        return Json(new { success = true, Message = "The product Deleted SuccessFully" });
       

        //return View(Obj);

    }
    #endregion
}

}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions