I am trying to use an EditorTemplate to display a child collection in a table in the parent’s view. The problem I have run into is that this only seems to work if the template is named exactly the same as child’s class. When I attempt to use a template with a slightly different name, and pass that name as the templateName argument to EditorFor,I get a runtime error. I was hoping I could use different child EditorTemplates for different purposes with the same child collection. Here is an abbreviated example:
Models:
public class Customer
{
int id { get; set; }
public string name { get; set; }
public List<Order> Orders { get; set; }
}
public class Order
{
public int id { get; set; }
public DateTime orderdate { get; set; }
public decimal amount { get; set; }
public Customer customer { get; set; }
}
Customer controller Index() method:
public ActionResult Index()
{
Customer customer = new Customer() {id = 1, name = "Acme Corp.", Orders = new List<Order>()};
customer.Orders.Add(new Order() {id = 1, orderdate = DateTime.Now, amount = 100M});
customer.Orders.Add(new Order() { id = 2, orderdate = DateTime.Now, amount = 200M });
return View(customer);
}
Customer Index.cshtml view:
@model TemplateTest.Customer
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Customer</title>
</head>
<body>
<div>
@Html.EditorFor(Model=>Model.name)
<table>
<thead>
<tr>
<th>Order ID</th>
<th>Order Date</th>
<th>Amount</th>
</tr>
</thead>
@Html.EditorFor(Model=>Model.Orders)
</table>
</div>
</body>
</html>
Order.cshmtl template in Views/Shared/EditorTemplates (added “color” to verify I am using this template):
@model TemplateTest.Order
<tr>
<td>@Html.DisplayFor(Model=>Model.id)</td>
<td style="color:blue">@Html.EditorFor(Model=>Model.orderdate)</td>
<td>@Html.EditorFor(Model=>Model.amount)</td>
</tr>
This works fine. But if I rename the EditorTemplate to “OrderList.cshtml” and change the child EditorFor line to
@Html.EditorFor(Model=>Model.Orders, "OrderList")
when I run it again I get this exception:
“The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[TemplateTest.Order]', but this dictionary requires a model item of type 'TemplateTest.Order'.”
Any idea why the EditorFor doesn’t use the template “OrderList” I specified in the “templateName" argument? Otherwise, what is that argument for?
color: blue
as a debugging aid won't actually show up visually. I'm too tired to explain why, but if you change it tobackground-color: blue
I think it will do what you want it to. ;) – Pricking