【问题标题】:Calling Action in Razor Pages在 Razor 页面中调用操作
【发布时间】:2019-05-22 12:42:24
【问题描述】:

作为 Razor Pages 的新手,我有一个关于从 Razor Page 调用方法的问题。

我的域模型中定义了一个名为subtractProduct 的方法。

在我的索引页面代码中,我定义了 IActionResult sellProduct,它在指定的 ProductId 上调用了 subproduct。但我不知道如何在我的 html 页面上调用此方法。我尝试了很多组合,但似乎没有任何效果。任何人都知道如何处理这个问题?非常感谢任何帮助!

我的领域模型是:

public class Product

{
    public int ProductId { get; set; }
    public int Quantity { get; set; }   
    ...
    public void SubtractProduct()
    {
        Quantity -= 1;
    }
}

我的索引页面代码是:

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();
    }
}

最后是我的 Razor 页面:

@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>

【问题讨论】:

    标签: c# razor asp.net-core .net-core razor-pages


    【解决方案1】:

    Razor 页面有 handler-methods,它们是 HTTP 动词。因此,要从您的页面调用方法,您需要输入On,然后是the http verb you want,然后是您的method name

    例如:

    public IActionResult OnGetSellProduct(int id)
    {
        var products = _context.Products;
    
        _context.Products.Find(id).SubtractProduct();
        return Page();
    }
    

    在您看来,将名称传递给asp-page-handler,不带OnPost or OnGet 前缀或Async 后缀。

    编辑:这是视图示例:

    <a asp-page-handler="SellProduct" asp-route-id="@item.ProductId">Sell Product</a>
    

    欲了解更多信息,请查看:

    Introduction to Razor Pages.

    Razor Pages Handler Methods.

    【讨论】:

    【解决方案2】:

    添加以下 tagHelper 和用户 asp-action="@Model.ReturnUrl" 以解析 Razor 页面中调用操作的 url

    @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
    

    【讨论】:

      猜你喜欢
      • 2020-11-17
      • 2019-05-01
      • 2020-07-11
      • 2019-02-23
      • 2022-01-12
      • 2020-05-26
      • 1970-01-01
      • 2014-03-25
      • 2020-01-27
      相关资源
      最近更新 更多