I have a button on the view page that connects to the another controller by passing an ID value.
Controller
public class CartController : Controller
{
......
[Route("index")]
public IActionResult Index()
{
var cart = SessionHelper.GetObjectFromJson<List<Item>>(HttpContext.Session, "cart");
ViewBag.cart = cart;
return View();
}
[Route("buy/{customerID}/{invetoryID}")]
public async Task<IActionResult> Buy(int? customerID, int? invetoryID)
{
if (customerID == null || invetoryID == null)
{
return NotFound();
}
Customer custData = await _context.Customers.FindAsync(customerID);
var intData = await _context.Inventories.FindAsync(invetoryID);
if (SessionHelper.GetObjectFromJson<List<Item>>(HttpContext.Session, "cart") == null)
{
List<Item> cart = new List<Item>();
cart.Add(new Item
{
Custom = custData,
Inventory = intData,
Quantity = 1
});
SessionHelper.SetObjectAsJson(HttpContext.Session, "cart", cart);
}
return RedirectToAction("Index");
} }}
Model
public class Item
{
public Customer Custom { get; set; }
public Inventory Inventory { get; set; }
public int Quantity { get; set; }
}
View is like below
<table cellpadding="2" cellspacing="2" border="1">
.......
@{var dataCart = ViewBag.cart; }
@foreach (var item in ViewBag.cart)
{
<tr>
<td>@item.Inventory.StrainId</td>
<td>@item.Inventory.StrainName</td>
<td>@item.Quantity</td>
</tr>
}
</table>
<br>
<a asp-action="Index" asp-controller="Inventories" asp-route-id="@dataCart.Custom.CustomerId">Select</a>
</body>
</html>
It throws error when I page is loaded it is throwing error like RuntimeBinderException: 'System.Collections.Generic.List<JAXSurplusMouseApp.Models.Item>' does not contain a definition for 'Custom'
Even though the Item model and the ViewBag has the Custom
it throws no definition. Can anyone tell what I am missing here. If I dont have the button then the page load perfectly fine.
<a asp-action="Index" asp-controller="Inventories" asp-route-id="@dataCart.Custom.CustomerId">Select</a>
CodePudding user response:
you have to fix your view
@if ( @ViewBag.cart != null && ViewBag.cart.Count>0)
{
<a asp-action="Index" asp-controller="Inventories" asp-route-id=" @ViewBag.cart[0].Custom.CustomerId">Select</a>
}
````
or place ancor inside of foreach
````
@foreach (var item in ViewBag.cart)
{
<tr>
<td>@item.Inventory.StrainId</td>
<td>@item.Inventory.StrainName</td>
<td>@item.Quantity</td>
<td>
<a asp-action="Index" asp-controller="Inventories" asp-route-id="@item.Custom.CustomerId">Select</a>
</td>
</tr>
}
</table>
<br>