Passing Parameters Using the Route Value
Learn about implementing parameter passing in ASP.NET Core using the action method, showcasing a concise test for retrieving product details via a web browser.
We'll cover the following...
We'll cover the following...
We’ll learn to pass parameters in ASP.NET Core. We’ll add an action method to the controller and create a corresponding view to display the output. Let’s dive into it.
Passing parameter
One way to pass a simple parameter is to use the id segment defined in the default route:
Step 1: In HomeController.cs
, add an action method named ProductDetail
, as shown in the following code:
Press + to interact
public IActionResult ProductDetail(int? id){if (!id.HasValue){return BadRequest("You must pass a product ID in the route, for example, / Home / ProductDetail / 21");}Product? model = db.Products.SingleOrDefault(p => p.ProductId == id);if (model is null){return NotFound($"ProductId {id} not found.");}return View(model); // pass model to view and then return result}
...