skip to Main Content

I Try to list in the same Create page the products I put to the same invoice. So I need insert my supplier invoices, off course in this invoice i have many products and I need to list in the same page where I create this invoice, so as soon as I insert the product it is appear on my list, I try to use partial view, but i can’t find the solution.

My controller

  [Area("***")]
    public class PurchaseController : Controller
    {
        private readonly IUnitOfWork _unitOfWork;

        public PurchaseController(IUnitOfWork unitOfWork)
        {
            _unitOfWork = unitOfWork;
        }

        public IActionResult Index()
        {
            IEnumerable<Purchases> objPurchaseList = _unitOfWork.Purchase.GetAll(includeProperties:"Suppliers").ToList();
            return View(objPurchaseList);
        }

        public IActionResult _CreatePartialView(string? invoice)
        {
            PurchaseVM purchaseVM = new()
            {
                purchases = new(),

              
            };

            if (invoice==null)
            {
                return RedirectToAction(nameof(Create));
            }

            List<Purchases> purchaseList = _unitOfWork.Purchase.GetAll().Where(u => u.PurchaseInvoice == invoice).ToList();
            return RedirectToAction(nameof(Create));
        }
        //GET
        public IActionResult Create()
        {
            PurchaseVM purchaseVM = new()
            {
                purchases = new(),

                GroupList = _unitOfWork.Group.GetAll().Select(u => new SelectListItem
                {
                    Text = u.GroupName,
                    Value = u.GroupId.ToString()
                }),

                SupplierList = _unitOfWork.Supplier.GetAll().Select(u => new SelectListItem
                {
                    Text = u.SupplierName,
                    Value = u.SupplierId.ToString()
                }),

                ProductList = _unitOfWork.Product.GetAll().Select(u => new SelectListItem
                {
                    Text = u.ProductName,
                    Value = u.ProductId.ToString()
                }),
            };

            return View(purchaseVM);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult Create(Purchases obj)
        {
            if(ModelState.IsValid)
            {
                _unitOfWork.Purchase.Add(obj);
                _unitOfWork.Save();
                TempData["success"]= "Product added successfully.";
                return View(obj);
            }
            return View();
        }
    }
}

My Partial View

@model IEnumerable<Purchases>


@foreach (var obj in Model.GroupBy(u => u.PurchaseInvoice))
{
    <tr>
        <td width="15%">
            @obj.First().PurcahseDate
        </td>
        <td width="15%">
            @obj.First().PurchaseInvoice
        </td>
        <td width="35%">
            @obj.First().Suppliers.SupplierName
        </td>
        <td width="15%" style="text-align:right">
            @obj.Sum(u => u.PurchaseTotal)
        </td>
        <td width="20%">
            <div class="w-75 btn-group" role="group">
                <a asp-controller="Purchase" asp-action="Edit" style="width:120px" asp-route-id="@obj.First().PurchaseInvoice"
                   class="btn btn-primary mx-2"> <i class="bi bi-pencil-square"></i> Edit</a>
                <a asp-controller="Purchase" asp-action="Delete" style="width:125px" asp-route-id="@obj.First().PurchaseInvoice"
                   class="btn btn-danger mx-2"> <i class="bi bi-trash-fill"></i> Delete</a>
            </div>
        </td>
    </tr>
}

My ViewModel

namespace SysComm.Models.ViewModels
{
    public class PurchaseVM
    {
        public Purchases purchases { get;set; }

        public List<Purchases> purchaseList { get; set; }

        [ValidateNever]
        public IEnumerable<SelectListItem> GroupList { get; set; }

        [ValidateNever]
        public IEnumerable<SelectListItem> SupplierList { get; set; }

        [ValidateNever]
        public IEnumerable<SelectListItem> ProductList { get; set; }
    }
}


Part off My View

            </div>
            <table class="table table-bordered table-striped" style="width:100%">
                <thead>
                    <tr>
                        <th>
                            Id
                        </th>
                        <th>
                            Date
                        </th>
                        <th>
                            Customer Name
                        </th>
                        <th>
                            Customer Phone
                        </th>
                        <th>
                            Action
                        </th>
                    </tr>
                </thead>
                <tbody>
                    <partial name="~/Areas/Admin/Views/Purchase/_CreatePartialView.cshtml" />
                </tbody>
            </table>
        </div>
    </div>
</div>

2

Answers


  1. I will use razor as a sample.
    First thing you need define your partial view.
    For instance in shared folder. Let’s name it "PagerPartial".

    At the top of your define the object you want to use like this:

    @model someclass
    

    After definition you can user this model like this in your razor page like this:

    <b>@Model.SomeProperty</b> item(s) listed
    

    After you complete your partial view you can use it in your other razor pages like this:

    @model SomeRazorProjectName.Pages.IndexModel
    
    <div>
    @await Html.PartialAsync("PagerPartial", Model.SomePropertyWithTypeOfSomeClass)
    </div>
    

    Note that "IndexModel" is the class of my razor page and "SomePropertyWithTypeOfSomeClass" is a property of type "someclass" defined in my page model.

    So, for you scenario you need to pass full product details (or just the id and let the partial view handle rest) to partial view to display as a row. You can adapt this according to your needs, but the basics same.

    Hope this helps.

    Login or Signup to reply.
  2. -> I think you are trying to display a list of purchases on the same page , in you create new purchase invoice and you want to update list dynamically according to new purchases added.

    -> Check your AJAX Url (/Purchase/_CreatePartialView) according to your application routing configuration.

    -> Modify your code :-

    -> PartialView(_CreatePartialView.cshtml) :-

    @model IEnumerable<Purchases>
    
    @foreach (var purchase in Model)
    {
      <tr>
        <td>@purchase.PurchaseId</td>
        <td>@purchase.PurchaseDate</td>
        <td>@purchase.Suppliers.SupplierName</td>
        <td>@purchase.Suppliers.SupplierPhone</td>
        <td>
            <!-- Action buttons -->
       </td>
     </tr>
    }
    

    -> Main View (where you create purchase invoice) and add script to load initially and update dynamically.
    code:-

    <div id="purchaseListContainer">
    <partial name="~/Areas/Admin/Views/Purchase/_CreatePartialView.cshtml" 
     model="Model.purchaseList" />
    </div>
    
     <!-- Script to update purchase list dynamically -->
    <script>
        $(document).ready(function () {
        updatePurchaseList();
    
        // Function to update the purchase list dynamically
        function updatePurchaseList() {
            $.ajax({
                url: '/Purchase/_CreatePartialView',
                type: 'GET',
                success: function (partialView) {
                    $('#purchaseListContainer').html(partialView);
                },
                error: function (xhr, status, error) {
                    console.error(xhr.responseText);
                }
            });
           }
        });
     </script>
    

    -> PurchaseController :-

    [HttpPost]
    [ValidateAntiForgeryToken]
    public IActionResult Create(Purchases obj)
    {
       if (ModelState.IsValid)
       {
        _unitOfWork.Purchase.Add(obj);
        _unitOfWork.Save();
        TempData["success"] = "Product added successfully.";
    
        // Return PartialView to update the purchase list
        return PartialView("_CreatePartialView", 
        _unitOfWork.Purchase.GetAll());
       }
    
      return View();
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search