我正在通过Udemy上的C#MVC 5应用程序进行工作,而我一直无法使用Html.ActionLink从视图中调用方法。我尝试过传递客户对象,然后决定尝试传递id。
由于我不知道/不知道的原因,这在显示正确的网址(/ CustomerController / CustomerView / 2)时抛出了HTTP 404错误。这是我的代码:
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>
}
当我单击表中的链接时,将引发http 404错误。非常感谢您的宝贵时间。
我认为适当的URI应该是(/ Customer / CustomerView / 2),而不应该是(/ Customer Controller / CustomerView / 2)。
下面是正确的代码行。
@ Html.ActionLink(customer.Name,“ CustomerView”,“ Customer”,新{id = customer.Id},null)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句