C# MVC 5 Html.ActionLInk

5k views Asked by At

I'm working through a C# MVC 5 application on Udemy, and I have gotten stuck on calling a method from the view, using Html.ActionLink. I've tried passing the customer object,then settled on trying to pass the id.

For a reason that I don't know/can't figure out, this is throwing an http 404 error, while displaying the proper Url ( /CustomerController/CustomerView/2). Here is my code:

RouteConfig.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace Vidly
{
public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapMvcAttributeRoutes();

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
}
}

CustomerController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Vidly.Models;

namespace Vidly.Controllers
{
public class CustomerController : Controller
{

    private List<CustomerModels> customers = new List<CustomerModels>
        {
            new CustomerModels {Id = 0, Name = "Theo Greer" },
            new CustomerModels {Id = 1, Name = "Mark Pate" },
            new CustomerModels {Id = 2, Name = "Jerry Jones" },
            new CustomerModels {Id = 3, Name = "Mary Alexander" },
            new CustomerModels {Id = 4, Name = "Patricia Smith" }
        };

    // GET: Customer
    public ActionResult Index()
    {
        return View(customers);
    }

    public ActionResult CustomerView(int id)
    {
        CustomerModels tempCust = customers.FirstOrDefault(CustomerModels => CustomerModels.Id == id);
        return View(tempCust);
    }
}
}

Index.cshtml

@model List<Vidly.Models.CustomerModels>
@{ }
<h2>Customers</h2>

<table class="table table-bordered table-hover">
<tr>
    <th>Customer</th>
</tr>
@foreach (var customer in Model)
{
    <tr><td>@Html.ActionLink(customer.Name, "CustomerView", "CustomerController", new { id = customer.Id }, null)</td></tr>
}

When I click on the links from the table, an http 404 error is thrown. Thank you very much for your time.

2

There are 2 answers

1
pgcan On BEST ANSWER

I think the proper URI should be (/Customer/CustomerView/2) and not (/CustomerController/CustomerView/2).

below is correct line of code.

@Html.ActionLink(customer.Name, "CustomerView", "Customer", new { id = customer.Id }, null)

0
anoj kattel On

Please Remove Controller From

<tr><td>@Html.ActionLink(customer.Name, "CustomerView", "CustomerController", new { id = customer.Id }, null)</td></tr>

Try This ActionLink Like..

<tr><td>@Html.ActionLink(customer.Name, "CustomerView", "Customer", new { id = customer.Id }, null)</td></tr>

It must be work..