Home > Net >  How to use Url.Action to get to the controller and also generate the url
How to use Url.Action to get to the controller and also generate the url

Time:12-02

When using this button

<a onclick="location.href='@Url.Action("Update", "Book", new { id = @Model.Id })'"
               class="btn btn-primary">Edit</a>

The controller indeed hits the get method

[HttpGet]
[Route("{id}")]
public ActionResult Update(int id) {...}

But the Url is not anymore matching the route {controller}/{action}, it just shows the id like this

https://localhost:44345/1

CodePudding user response:

You are overriding the entire route when you use the [Route()] attribute on your endpoint, this is why the controller name portion is removed. I imagine the reason you have done this is due to a conflict with an existing GET action.

You appear to be using a GET request to update your entity. Instead use POST or PUT depending on the scenario (https://www.w3schools.com/tags/ref_httpmethods.asp) and update your HttpGet attribute accodingly.

[HttpPost]
// or
[HttpPut]

and ensure that you have a route attribute on your controller class that looks like this:

[Route("[controller]")]
public class BookController : ControllerBase

This will ensure that the controller portion of the route is included, so the format will be: .../{controllerName}/{id}

NOTE: If you want to stick with GET and have multiple requests of the same HTTP message type then you can route to the correct action by updating the [HttpGet] attribute rather than adding a [Route] attribute :

[HttpGet("update/{id}")]

This will give your url the following format .../{controllerName}/update/{id}

CodePudding user response:

you can use an ancor helper

<a asp-action="Update" asp-controller="Book" asp-route-id="@Model.Id" class="btn btn-primary">Edit</a>
  • Related