简体   繁体   中英

Asp.net core -> How to Delete Row from table with pKey(invoice_id, row_id)

I'm using MS SQL Server 2014, Visual Studio 2019, ASP.NET Core 5.0 with C#.

After having created two tables - Invoice and Rows

Invoice {inv_id, client, address}
Rows {inv_id, row_id, product, price}

the "Invoice table has pkey= inv_id"
the "Rows table has pkey=(inv_id,row_id)"

When I click on the delete button (on Index) it asks for two parameters but, asp-route-id permits only one id.

The Delete button is:

a asp-page="./Delete" asp-route-id="@item.row_id" class="btn" 

How can I solve this?

asp-route-[parameter] can multiple parameters. For example:

<a asp-page="./Delete" asp-route-rowid="@item.row_id" asp-route-invid="@item.inv_id" class="btn">

Take the rowid and invid as the parameter in the bakend.

public ActionResult Delete(int invId, int rowId)()
{

}

Here is the official introduction .

Thank you very much to both. I had to combine both of the answers to make it work.

This is the solution that worked for me: (lets hope it helps someone else too)

Index.cshtml ==>

a asp-page="./Delete" asp-route-invid="@item.invId" asp-route-rowid="@item.rowId" class="btn btn-danger"

Index.cshtml.cs ==> (Unchanged)

Delete.cshtml ==> (Unchanged)

Delete.cshtml.cs ==>

    [BindProperty]
    public InvoiceRows InvoiceRows { get; set; }

    public async Task<IActionResult> OnGetAsync(int? invid, int rowid)
    {
        if (invid < 0)
        {
            return NotFound();
        }

        InvoiceRows= await _context.InvoiceRows.Where(r => r.rowid== rowid)
            FirstOrDefaultAsync(m => m.invid== invid);

        if (InvoiceRows== null)
        {
            return NotFound();
        }
        return Page();
    }

    public async Task<IActionResult> OnPostAsync(int invid, int rowid)
    {
        if (invid< 0 || rowid< 0)
        {
            return NotFound();
        }

        InvoiceRows= await _context.InvoiceRows.FindAsync(invid, rowid);

        if (InvoiceRows!= null)
        {
            _context.InvoiceRows.Remove(InvoiceRows);
            await _context.SaveChangesAsync();
        }

        return RedirectToPage("./Index");
    }

RowsController.cs ==>

(Delete controller)

    [Route("~/Rows/delete/{invId}/{rowId}")]
    **public async Task<ActionResult> Delete**(int invId, int rowId)
    {
        if (invId< 0 || rowId< 0)
        {
            return NotFound();
        }

        var InvoiceRows= await _context.InvoiceRows.Where(r => r.rowId== rowId)
            .FirstOrDefaultAsync(m => m.invId== invId);
        if (InvoiceRows == null)
        {
            return NotFound();
        }

        return View(InvoiceRows);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM