iivo
iivo

Reputation: 47

ASP .Net Core Routing issue?

I am following an ASP.NET Core MVC Course (.NET 5) tutorial on youtube. I am getting error "This localhost page can’t be found" when I click on the EDIT button, used to redirect me to partial view of Category Models. I have no code mistakes since I am following the tutorial line by line. My routing seems okay:

app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
        });

Here is the Index view for Category:

<tbody>
            @foreach (var obj in Model)
            {
                <tr>
                    <td width="50%">@obj.Name</td>
                    <td width="30%">@obj.DisplayOrder</td>
                    <td class="text-center">
                        <div class="w-75 btn-group" role="group">
                            <a asp-controller="Category" asp-all-route-Id="@obj.Id" asp-action="Edit" class="btn btn-primary mx-2">
                                Edit
                            </a>
                            <a asp-controller="Category" asp-all-route-Id="@obj.Id" asp-action="Delete" class="btn btn-danger mx-2">
                                Delete
                            </a>
                        </div>
                    </td>
                </tr>
            }
        </tbody>

And my action method for edit:

//GET -  EDIT
    public IActionResult Edit(int? id)
    {
        if(id == null || id == 0)
        {
            return NotFound();
        }
        var obj = _db.Category.Find(id);
        if(obj == null)
        {
            return NotFound();
        }

        return View(obj);
    }

Index View for Category

Upvotes: 2

Views: 742

Answers (1)

Kirk Larkin
Kirk Larkin

Reputation: 93293

There's an issue with this line:

<a asp-controller="Category"
   asp-all-route-Id="@obj.Id"
   asp-action="Edit"
   class="btn btn-primary mx-2">

asp-all-route-Id isn't something that the Anchor Tag Helper recognises. Because of this, the value @obj.Id isn't being passed into the Edit action, so its int? id parameter isn't being set. This means the return NotFound(); line runs and generates the 404 response.

Instead, you need asp-route-id. For completeness, here's the updated version:

<a asp-controller="Category"
   asp-route-id="@obj.Id"
   asp-action="Edit"
   class="btn btn-primary mx-2">

You haven't mentioned the Delete action, but this appears to suffer from the same issue.

Upvotes: 1

Related Questions