I have the following action button on a View. The View is located on InventoryRequest Index (list). So when the button is clicked, it will redirect to another View which is InventoryRequestDetails – Index:
<a asp-controller="InventoryRequestDetails" asp-action="Index" asp-route-id="@item.InventoryRequestId">Details</a>
Then on the InventoryRequestDetails Controller – Index. I put the following code:
public async Task<IActionResult> Index(int InventoryRequestId)
{
_logger.LogInformation($"Finding InventoryRequest with ID {InventoryRequestId}");
// Select the InventoryRequest object with the specified InventoryRequestId
var inventoryRequest = await _context.InventoryRequests.FindAsync(InventoryRequestId);
_logger.LogInformation($"Found InventoryRequest: {inventoryRequest}");
// Check if an InventoryRequest object was found
if (inventoryRequest == null)
{
return NotFound();
}
// Store the value of the RequestNumber property in a ViewBag object
ViewBag.RequestNumber = inventoryRequest.RequestNumber;
// Retrieve the InventoryRequestDetails data for the specified InventoryRequestId
var applicationDbContext = _context.InventoryRequestDetails
.Include(i => i.Inventaris)
.Include(i => i.InventoryRequest)
.Where(w => w.InventoryRequestId == InventoryRequestId);
// Return the view with the InventoryRequestDetails data and the RequestNumber value in the ViewBag
return View(await applicationDbContext.ToListAsync());
}
The thing is, I couldn’t get the RouteID that has been passed into the URL in InventoryRequestDetails. The URL is something like this:
https://localhost:xxxx/InventoryRequestDetails/Index/1
I want to get the Id value which is "1" on the URL above. How can I do that? Are there any mistakes in my code? Please advise.
After I get the value, I want to create another list which is filtered by the value.
Thank you.
>Solution :
Three approaches to fix:
- Change the
asp-routename:asp-route-inventoryRequestId
<a asp-controller="InventoryRequestDetails" asp-action="Index" asp-route-inventoryRequestId="@item.InventoryRequestId">Details</a>
- In the controller action, change the property name
InventoryRequestIdtoid.
public async Task<IActionResult> Index(int id)
- Work with the route:
[HttpGet("{InventoryRequestId}")]
public async Task<IActionResult> Index(int InventoryRequestId)
Reference: Model binding