Hi @Jerry Lipan ,
How to access data
Product(Id)
Product(Title)
Quantity
And so on ?
To access the Product from the Cart, you could use foreach
or for
loop statement to loop through the list, then access the value from the navigation property (the Product property in the Cart class).
Refer the following code:
Controller:
public IActionResult CartIndex()
{
//get the cart data:
List<Cart> datacart = _datarepo.GetCarts();
//use foreach or for statement to loop the list
foreach (var item in datacart)
{
Console.WriteLine("Product Id: {0} Product Title: {1} Quantity: {2}", item.Product.Id, item.Product.Title, item.Quantity.ToString());
}
return View(datacart);
}
If you want to access the value in the view page, the code like this:
[Note] In the View page, if you want to list and update the value first, and then submit the updated the value to the controller, in this scenario, you'd better use for
loop statement to display the page model data.
@model IEnumerable<MVCWebApp.Models.Cart>
@{
ViewData["Title"] = "CartIndex";
}
<table class="table">
<thead>
<tr>
<th>Product Id</th>
<th>Product Title</th>
<th>
@Html.DisplayNameFor(model => model.Quantity)
</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Product.Id)
</td>
<td>
@Html.DisplayFor(modelItem => item.Product.Title)
</td>
<td>
@Html.DisplayFor(modelItem => item.Quantity)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
</td>
</tr>
}
</tbody>
</table>
The output like this:
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
Best regards,
Dillion