Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

save and edit table take its data from dropdownlist from other table using .net framework core using c# and sqlserver #44509

Open
JmalSalih opened this issue Jan 24, 2025 · 0 comments

Comments

@JmalSalih
Copy link

JmalSalih commented Jan 24, 2025

Type of issue

Code doesn't work

Description

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using PurchaseSystem.Models;

namespace PurchaseSystem.Controllers
{
public class InvoicesController : Controller
{
private readonly ApplicationDbContext _context;

    public InvoicesController(ApplicationDbContext context)
    {
        _context = context;
    }

    // GET: Invoices
    public async Task<IActionResult> Index()
    {
        var applicationDbContext = _context.Invoices.Include(i => i.Product).Include(i => i.Supplier).Include(i => i.Unit);
        return View(await _context.Invoices.ToListAsync());
    }

    // GET: Invoices/Details/5
    public async Task<IActionResult> Details(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var invoices = await _context.Invoices
            .Include(i => i.Product)
            .Include(i => i.Supplier)
            .Include(i => i.Unit)
            .FirstOrDefaultAsync(m => m.InvoiceID == id);
        if (invoices == null)
        {
            return NotFound();
        }

        return View(invoices);
    }

    // GET: Invoices/Create
    //public IActionResult Create()
    //{
    //    ViewData["ProductID"] = new SelectList(_context.Products, "ProductID", "ProductName");
    //    ViewData["SupplierID"] = new SelectList(_context.Suppliers, "SupplierID", "SupplierName");
    //    ViewData["UnitID"] = new SelectList(_context.Units, "UnitID", "UnitName");
    //    return View();
    //}

    //// POST: Invoices/Create
    //// To protect from overposting attacks, enable the specific properties you want to bind to.
    //// For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
    //[HttpPost]
    //[ValidateAntiForgeryToken]
    //public async Task<IActionResult> Create([Bind("InvoiceID,UnitID,SupplierID,ProductID,Quantity,InvoiceDate")] Invoices invoices)
    //{
    //    if (ModelState.IsValid)
    //    {
    //        _context.Add(invoices);
    //        await _context.SaveChangesAsync();
    //        return RedirectToAction(nameof(Index));
    //    }
    //    ViewData["ProductID"] = new SelectList(_context.Products, "ProductID", "ProductName", invoices.ProductID);
    //    ViewData["SupplierID"] = new SelectList(_context.Suppliers, "SupplierID", "SupplierName", invoices.SupplierID);
    //    ViewData["UnitID"] = new SelectList(_context.Units, "UnitID", "UnitName", invoices.UnitID);
    //    return View(invoices);
    //}

    // GET: Invoices/Create
    public IActionResult Create()
    {
        ViewData["UnitID"] = new SelectList(_context.Units, "UnitID", "UnitName");
        ViewData["SupplierID"] = new SelectList(_context.Suppliers, "SupplierID", "SupplierName");
        ViewData["ProductID"] = new SelectList(_context.Products, "ProductID", "ProductName");
        return View();
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Create([Bind("InvoiceID,UnitID,SupplierID,ProductID,Quantity,InvoiceDate")] Invoices invoice)
    {
        if (ModelState.IsValid)
        {

            try
            {
                var errors = ModelState.Values.SelectMany(v => v.Errors);
                foreach (var error in errors)
                {
                    Console.WriteLine(error.ErrorMessage);
                }
            

           
                _context.Add(invoice);
                await _context.SaveChangesAsync();
                string message = "Created the record successfully";

                // To display the message on the screen
                // after the record is created successfully
                ViewBag.Message = message;
                return RedirectToAction(nameof(Index));
                

            }
            catch (DbUpdateException ex)
            {
                // Log the error (uncomment the following line if you have a logger)
                // _logger.LogError(ex, "An error occurred while saving the invoice.");
                ModelState.AddModelError("", "Unable to save changes. Please try again.");
            }
        }

        // If we got this far, something failed; redisplay the form with validation errors
        ViewData["UnitID"] = new SelectList(_context.Units, "UnitID", "UnitName", invoice.UnitID);
        ViewData["SupplierID"] = new SelectList(_context.Suppliers, "SupplierID", "SupplierName", invoice.SupplierID);
        ViewData["ProductID"] = new SelectList(_context.Products, "ProductID", "ProductName", invoice.ProductID);
        return View(invoice);
    }
    // GET: Invoices/Edit/5
    public async Task<IActionResult> Edit(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var invoices = await _context.Invoices.FindAsync(id);
        if (invoices == null)
        {
            return NotFound();
        }
        ViewData["ProductID"] = new SelectList(_context.Products, "ProductID", "ProductName", invoices.ProductID);
        ViewData["SupplierID"] = new SelectList(_context.Suppliers, "SupplierID", "SupplierName", invoices.SupplierID);
        ViewData["UnitID"] = new SelectList(_context.Units, "UnitID", "UnitName", invoices.UnitID);
        return View(invoices);
    }

    // POST: Invoices/Edit/5
    // To protect from overposting attacks, enable the specific properties you want to bind to.
    // For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Edit(int id, [Bind("InvoiceID,UnitID,SupplierID,ProductID,Quantity,InvoiceDate")] Invoices invoices)
    {
        if (id != invoices.InvoiceID)
        {
            return NotFound();
        }

        if (ModelState.IsValid)
        {
            try
            {
                _context.Update(invoices);
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!InvoicesExists(invoices.InvoiceID))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }
            return RedirectToAction(nameof(Index));
        }
        ViewData["ProductID"] = new SelectList(_context.Products, "ProductID", "ProductName", invoices.ProductID);
        ViewData["SupplierID"] = new SelectList(_context.Suppliers, "SupplierID", "SupplierName", invoices.SupplierID);
        ViewData["UnitID"] = new SelectList(_context.Units, "UnitID", "UnitName", invoices.UnitID);
        return View(invoices);
    }

    // GET: Invoices/Delete/5
    public async Task<IActionResult> Delete(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var invoices = await _context.Invoices
            .Include(i => i.Product)
            .Include(i => i.Supplier)
            .Include(i => i.Unit)
            .FirstOrDefaultAsync(m => m.InvoiceID == id);
        if (invoices == null)
        {
            return NotFound();
        }

        return View(invoices);
    }

    // POST: Invoices/Delete/5
    [HttpPost, ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> DeleteConfirmed(int id)
    {
        var invoices = await _context.Invoices.FindAsync(id);
        if (invoices != null)
        {
            _context.Invoices.Remove(invoices);
        }

        await _context.SaveChangesAsync();
        return RedirectToAction(nameof(Index));
    }

    private bool InvoicesExists(int id)
    {
        return _context.Invoices.Any(e => e.InvoiceID == id);
    }
}

}

[Enter feedback here]

Page URL

https://learn.microsoft.com/en-us/dotnet/framework/tools/mdbg-exe

Content source URL

https://github.com/dotnet/docs/blob/main/docs/framework/tools/mdbg-exe.md

Document Version Independent Id

a9a112c9-722e-f557-7935-1a0605c320ee

Article author

@gewarren

Metadata

  • ID: 51c332c8-7b56-fdcf-f2c8-006cb54d7fb0
  • Service: dotnet-framework

Related Issues

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant