Search code examples
c#razorasp.net-core-mvcasp.net-core-6.0

Razor MVC - Post a model object to a controller action when button is pressed


Within an ASP.NET Core 6 MVC web app with Razor pages, I have a view about a product gallery (in this case pharmacy items) and each item card in the gallery has a button "Add to basket". When this button is pressed, I would like to send the product item to the AddToBasket action of the BasketController. The application can be found here.

In tutorials I have only seen it being solved with a form, collecting user input and binding that input to model properties to then submit it to a controller. I don't need to collect any user input, the item model object is already there in the view:

@model IEnumerable<Razor.Pharmacy.Domain.Entities.PharmacyItem>

<div class="container">
    <div class="row">
        @foreach (var item in Model) {
            ...
            <a href="@Url.Action("AddToBasket", "Basket", new { customerId = 0, item = item })" class="btn btn-dark">Add To Basket</a>
            ...
        }
    </div>
</div>

Here is the controller action

// BasketController.cs

public void AddToBasket(int customerId, PharmacyItem item)
{
    _basketService.AddItemToBasket(customerId, item);
}

However, when I now press the "Add to basket" link, I don't get the intended item model object in the controller action method but an object with the default values

 {Razor.Pharmacy.Domain.Entities.PharmacyItem}
    ItemId: 0
    Name: null
    Price: 0
    Quantity: 0
    RequiresPrescription: false

Thanks for the help


Solution

  • The complex model cannot be serialized dynamically( You can F12 in the browser to check the generated url) in your scenario. You need specify the property like below:

    <a href="@Url.Action("AddToBasket", "Basket", new { customerId = 0, ItemId = item.ItemId,Name=item.Name,Price=item.Price})" class="btn btn-dark">Add To Basket</a>