Pass jQuery data from View to Controller and save it as many-to-many

Lancis007 41 Reputation points
2021-07-20T01:15:40.337+00:00

Hi, can you help ?

I have a many to many relationship.

I generated controller and view for the 2 below entities (Product and Invoice) from scaffolding in asp.net 3.0 and ef core 3.1

I'm able to do CRUD from both entities.

I have a requirement, in Invoice View page I need to have a Dropdown that is fed from Product table and add ItemName into the dropdownlist.
I did it already thru ViewData["Products"] and it works fine.

Another requirement, when user select from that dropdownlist, there an 'Add item' button next to it,
if the user click on that 'Add item' button, the item name must be added below on the page (I did it already thru jquery and its works)

The page has a Save button at the bottom, when clicked, it's only pass the Invoice model to the controller thru Binding (it's the correct behavior),
but I'm not sure how to pass all the added items (only their Id) to the controller to be saved in the join-table (ProductInvoice).

Not sure maybe I did not design the architecture of the application properly that's why I wrote the whole scenario/use-case maybe you can suggest me to redesign.

In brief, the use-case is : user must add itemName (fetch from Product table) to the invoice and save it as many-to-many relationship.

I searched the whole day, I could'nt find how to do it that's the reason of my post.

public class Product
{
    public int ProductId { get; set; }

    public int Price { get; set; }

    public string ItemName { get; set; }

    public IList<ProductInvoice> ProductInvoices { get; set; }
}

 public class Invoice
{
    public int InvoiceId { get; set; }

    public DateTime InvoiceDate { get; set; }

    public IList<ProductInvoice> ProductInvoices { get; set; }
}

    public class ProductInvoice
    {
        [Key]
        public int ProductId { get; set; }
        public Product Product { get; set; }

        [Key]
        public int InvoiceId { get; set; }
        public Invoice Invoice { get; set; }
    }


 [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Create([Bind("InvoiceId,CreatedDate,CreateByUser,TotalInvoice")] Invoice invoice)
    {
        if (ModelState.IsValid)
        {
            _context.Add(invoice);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }
        return View(invoice);
    }




<script>
        $(document).ready(function () {

            var totalInvoice = 0;

            $("#btn-add-item").click(function () {

                var selectedItem = $('#SelectedProducts :selected').text();
                var getCostPerItem = $('#SelectedProducts :selected').val();

                getCostPerItem = getCostPerItem.split("-")[1];
                getCostPerItem = getCostPerItem.split(".")[0];
                totalInvoice = parseInt(totalInvoice) + parseInt(getCostPerItem);

                $('<div id="created_div">' + '<b>+</b> ' + selectedItem + ' :  $ ' + ' ' + getCostPerItem + '<a href="#" class="btn btn-danger btn-sm btn-remove-item float-right">Remove</a></div><br>').insertAfter('#main-body-card');
                $("#total-invoice-input").val(totalInvoice);
            });

        });
    </script>
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,212 questions
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,292 questions
{count} votes

6 answers

Sort by: Most helpful
  1. Lancis007 41 Reputation points
    2021-07-20T10:47:10.073+00:00

    I added the code you suggested in stackoverflow,
    when I run to test it, the ProductInvoices arguments in Create Method, Bind attribute show Null.

    But on the browser I can see it creates the hidden field properly.
    By the way, in the Model invoice I don't have a property called ProductInvoices.

    Do I need to add it ?

    0 comments No comments

  2. Lancis007 41 Reputation points
    2021-07-20T11:45:37.797+00:00

    @Rena Ni - MSFT Can you please help ? I'm getting null value in ProductInvoices paramater.


  3. Lancis007 41 Reputation points
    2021-07-20T11:58:16.563+00:00

    I fixed Null value from ProductInvoices paramater. I was missing one thing.

    0 comments No comments

  4. Lancis007 41 Reputation points
    2021-07-20T12:15:14.967+00:00

    A new issue occurred. I'm getting Price value instead of real ProductId in ProductInvoices parameter of Create POST method.

    0 comments No comments

  5. Lancis007 41 Reputation points
    2021-07-20T12:35:02.293+00:00

    Thanks. It's all fixed. It's my own mistake. Your code working as expected.

    Thanks again for your help Rena.

    0 comments No comments