在Razor页面中调用操作

xce*_*elm 3 c# razor .net-core asp.net-core razor-pages

作为Razor Pages的新手,我对从Razor Page调用方法有疑问。

我在我的域模型中定义了一个名为减去产品的方法。

在我的索引页代码中,我定义了IActionResult sellProduct,该产品在指定的ProductId上调用excludeProduct。但是我不知道如何在我的html页面上调用此方法。我尝试了很多组合,但似乎没有任何效果。有人知道如何处理吗?任何帮助是极大的赞赏!

我的域模型是:

public class Product

{
    public int ProductId { get; set; }
    public int Quantity { get; set; }   
    ...
    public void SubtractProduct()
    {
        Quantity -= 1;
    }
}
Run Code Online (Sandbox Code Playgroud)

我的索引页代码是:

public class IndexModel : PageModel
{
    private readonly CfEshop.Data.ApplicationDbContext _context;

    public IndexModel(CfEshop.Data.ApplicationDbContext context)
    {
        _context = context;
    }

    public IList<Models.Product> Product { get;set; }

    public async Task OnGetAsync()
    {
        Product = await _context.Products
            .Include(p => p.Categories).ToListAsync();
    }

    public IActionResult sellProduct(int id)
    {
        var products = _context.Products;

        _context.Products.Find(id).SubtractProduct();
        return Page();
    }
}
Run Code Online (Sandbox Code Playgroud)

最后我的剃刀页面:

@page
@model CfEshop.Pages.Product.IndexModel
<h2>Index</h2>

<table class="table">
    <thead>
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.Product[0].Quantity)
            </th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model.Product)
        {
            <tr>
                <td>
                    @Html.DisplayFor(modelItem => item.Quantity)
                </td>
                <td>
                    <a asp-page-handler="SellProduct" asp-route="@item.ProductId">Sell Product</a>
                </td>
            </tr>
        }
    </tbody>
</table>
Run Code Online (Sandbox Code Playgroud)

Ham*_*eed 8

剃刀页面具有handler-methodsHTTP动词。因此,要从您的页面调用方法,您需要先放置Onthe http verb you want然后再放置method name

例如:

public IActionResult OnGetSellProduct(int id)
{
    var products = _context.Products;

    _context.Products.Find(id).SubtractProduct();
    return Page();
}
Run Code Online (Sandbox Code Playgroud)

并在您的视图中将名称传递给asp-page-handler不带OnPost or OnGet前缀或Async后缀的。

编辑:这是视图示例:

<a asp-page-handler="SellProduct" asp-route-id="@item.ProductId">Sell Product</a>
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请查看以下内容:

剃刀页简介

剃刀页处理方法