So I have a parent class called Item:
public class Item {
public Guid Id {get; set;}
public double Price {get; set;}
}
The Bread and Cookie class inherit from this class:
public class Bread : Item {
public string Type {get; set;}
}
public class Cookie : Item {
public string Flavour {get; set;}
public string Size {get; set;}
}
I display these in a table on a Razor View with a "AddToCart" button.
@using Data.Entities
@model ViewModels.CookieIndexViewModel
@{
ViewBag.Title = "Cookie list";
}
<h1>Our collection of cookies:</h1>
<table class="table">
@foreach (var cookie in Model.Cookies)
{
<tr>
<td>@cookie.Flavour</td>
<td>@cookie.Size</td>
<td>@cookie.Price</td>
<td><a class="btn btn-primary text-white" asp-action="AddItem" asp-controller="Cart" asp-route-item="@cookie">Purchase</a></td>
</tr>
}
</table>
And in the CartController I have the methode AddItem that takes an Item as parameter
public IActionResult AddItem(Item item)
{
return View();
}
But this doesn't work because Cookie can not be converted to an Item any tips on how to do this?
But this doesn't work because Cookie can not be converted to an Item any tips on how to do this?
That's not the issue here. What you are trying to do is stuff a model (a complex tyep) into a single parameter. That's not how http query parameters works and not how MVC model binding works.
Take your Controller action:
public IActionResult AddItem(Item item)
This won't try to bind a single property called item
. It will try to parse the properties of the model (id
, price
). So you need to be passing these individually.
My solution would be to pass just the item id. Why would you need to pass the price? That's a security issue. Someone might change the price in the request!?
<tr>
<td>@cookie.Flavour</td>
<td>@cookie.Size</td>
<td>@cookie.Price</td>
<td><a class="btn btn-primary text-white" asp-action="AddItem" asp-controller="Cart" asp-route-id="@cookie.Id">Purchase</a></td>
</tr>
public IActionResult AddItem(Guid id)
{
//lookup item
//add to cart
return View();
}