简体   繁体   中英

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

I have a lot of experience with ASP.NET MVC 1-5 . Now I learn ASP.NET Core MVC and have to pass a parameter to link in page. For example I have the following Action

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

How can I implement the link for this action using tag helpers?

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

You can use the attribute prefix asp-route- to prefix your route variable names.

Example:

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

You might want to apply the following syntax.

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

That will produce the call route like this.

/Member/Edit/3/full/12

Then you can receive it in the method as shown below.

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

Although, the attribute decorating the method isn't required in MVC, it shows more clearly how to bind the attributes from the link to the passed in parameters in the method.

if you want to put variable id into link in grid or table something below code can be used

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

On the back-end:

This code must write at the top of the action in the controller

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

On the front-end:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM