作为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;
}
}
我的索引页代码是:
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();
}
}
最后我的剃刀页面:
@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>
剃刀页面具有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>
有关更多信息,请查看以下内容:
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句