簡體   English   中英

如何在 ASP.NET Core MVC 中向 asp 標簽助手添加鏈接參數

[英]How to add link parameter to asp tag helpers in ASP.NET Core MVC

我在ASP.NET MVC 1-5方面有很多經驗。 現在我學習了ASP.NET Core MVC並且必須傳遞一個參數來鏈接頁面。 例如我有以下操作

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

如何使用標簽助手實現此操作的鏈接?

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

您可以使用屬性前綴asp-route-為您的路由變量名稱添加前綴。

示例:

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

您可能希望應用以下語法。

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

這將產生這樣的呼叫路由。

/成員/編輯/3/full/12

然后就可以通過如下所示的方法接收了。

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

雖然在MVC中不需要裝飾方法的屬性,但它更清楚地展示了如何將來自鏈接的屬性綁定到方法中傳入的參數。

如果您想將變量 id 放入網格或表格中的鏈接中,可以使用以下代碼

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


 <a  asp-controller="Product" asp-action="GetProduct" asp-route-id="@item.id" >ProductName</a>

在后端:

這段代碼必須寫在控制器中動作的頂部

[Route("/Controller/Method/{Object or varible name}")]
public actionresult method name(your variable)
{
    //your code...
}

在前端:

@{
var url = "/Controller/Method/" + your data;
<a href="@url"> click me for send data()</a>
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM