skip to Main Content

I have previously implemented a onclick event inside a <label> tag as shown below

<label onclick="window.location='/edit/@(editId)'">edit<lable>

but now, I want to use only tag helpers to generate links using tag helpers like asp-page, asp-route-editId etc.

how can I build above onclick url with asp-tag helpers

2

Answers


  1. In this scenario, you have to create the url directly, you can’t use Anchor Tag Helper attributes because they create attributes like href for you. But here you have to create the link directly and use it in the onclick event:

    if using MVC:

    //replace ActionName and ControllerName with correct values                                     
    @Url.Action("ActionName","ControllerName",new{editId})
    

    if using Razor Page:

    //replace id name with correct parameter name
    @Url.Page("/Edit",new {id=editId })
    

    Finally, your code should be as follows(for razor page link)

    //replace id name with correct parameter name
    <label onclick="window.location='@Url.Page("/Edit",new {id=editId })'">edit</label>
    

    One important note:

    If your input parameter name is editid, you can omit the parameter name in route values, but if it has a different name, for example, itemId, you must explicitly specify the parameter name. As follows

    <label onclick="window.location='@Url.Page("/Edit",new {itemId = editId })'">edit</label>
    
    Login or Signup to reply.
  2. If you want to use anchor tag helper,you need to use <a></a>,if you want to remove the underline and change the color,you can try to add the following styles:

    <a asp-action="edit" asp-route-editId="1" style="color:black;text-decoration:initial">edit</a>
    

    But in this way,you will have the route like:

    https://localhost:.../edit?editId={id}
    

    So that you need to change the route backend.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search