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>