Reputation: 41
I'm working with .NET MVC-5. And I'm getting the above error. In my case I have a controller named as "Customer-controller". Which consists of two Action Results named as "Index" and "Details".
Index is rendering a list of customers from database. The question is if I click on any of name in the list of customers (rendered by "Index") should redirect me to details action Result and show the details related to specific customer.
Customer Controller
public class CustomerController : Controller
{
private ApplicationDbContext _context;
public CustomerController()
{
_context = new ApplicationDbContext();
}
protected override void Dispose(bool disposing)
{
_context.Dispose();
}
// GET: Customer
public ActionResult Index()
{
var customers = _context.Customers.ToList();
return View(customers);
}
public ActionResult Details(int id)
{
var cus = _context.Customers.FirstOrDefault(c=> c.Id==id);
if (cus == null)
return HttpNotFound();
return View(cus);
}
}
Index cshtml
<table class="table table-bordered table-responsive table-hover">
<thead>
<tr>
<th>Customer Name</th>
</tr>
</thead>
<tbody>
@foreach (var i in Model)
{
<tr>
<td>@Html.ActionLink(@i.Name, "Details", "Customer", new {id=1 }, null)</td>
</tr>
}
</tbody>
Detail cshtml
<table class="table table-bordered table-hover table-responsive">
<thead>
<tr>
<th>Customer Id</th>
<th>Customer Name</th>
</tr>
</thead>
<tbody>
@foreach (var i in Model)
{
<tr>
<td> @i.Id @i.Name </td>
</tr>
}
</tbody>
Upvotes: 1
Views: 263
Reputation: 1720
you are selecting data using FirstOrDefault
, so it will return single entity object of Customers
class and you are trying to iterate it, which is wrong.
here, you can resolve it using 2 ways.
1) Here you will get object value without foreach
like below.
<table class="table table-bordered table-hover table-responsive">
<thead>
<tr>
<th>Customer Id</th>
<th>Customer Name</th>
</tr>
</thead>
<tbody>
<tr>
<td> @i.Id @i.Name </td>
</tr>
</tbody>
2) If you do not want to change View code, then you need to pass list
object from controller like below.
public ActionResult Details(int id)
{
var cus = _context.Customers.FirstOrDefault(c=> c.Id==id);
List<Customers> lstcus = new List<Customers>();
lstcus.Add(cus);
if (cus == null)
return HttpNotFound();
return View(lstcus);
}
Upvotes: 3