如何在ASP.NET Core MVC中向asp标记助手添加链接参数

问题描述 投票:70回答:2

我对ASP.NET MVC 1-5有很多经验。现在我学习ASP.NET Core MVC并且必须将参数传递给页面中的链接。例如,我有以下Action

 [HttpGet]
 public ActionResult GetProduct(string id)
 {
      ViewBag.CaseId = id;
      return View();
 }

如何使用标记帮助程序实现此操作的链接?

<a asp-controller="Product" asp-action="GetProduct">ProductName</a>
c# asp.net-core asp.net-core-mvc url-parameters tag-helpers
2个回答
151
投票

您可以使用属性前缀asp-route-为路径变量名称添加前缀。

例:

<a asp-controller="Product" asp-action="GetProduct" asp-route-id="10"> ProductName</a>

9
投票

您可能希望应用以下语法。

<a asp-controller="Member"
   asp-action="Edit"
   asp-route-level="3"
   asp-route-type="full"
   asp-route-id="12">Click me</a>

这将产生这样的呼叫路由。

/会员/编辑/ 3 /全/ 12

然后你可以用如下所示的方法接收它。

[Route({level}/{type}/{id})]
public IActionResult Edit(int level, string type, int id) { ... }

尽管在MVC中不需要修饰该方法的属性,但它更清楚地显示了如何将链接中的属性绑定到方法中的传入参数。

© www.soinside.com 2019 - 2024. All rights reserved.