When trying to loop through data in a View that is returned from a controller, I get an error ” ‘object’ does not contain a definition for ‘CustomerID’ and no extension method ‘CustomerID’ accepting a first argument of type ‘object’ could be found”
Here is my view
<% using (Html.BeginForm()) {%>
<%foreach (var item in (IEnumerable)Model)
{ %>
<%= Html.Encode(item.CustomerID) %>
<%} %>
<% } %>
Here is the controller:
public ActionResult Index()
{
Models.NorthwindDataContext nw = new Models.NorthwindDataContext();
var qry = from ord in nw.Orders
join cust in nw.Customers on ord.CustomerID equals cust.CustomerID
select new Models.OrdersModel
{
CustomerID = ord.CustomerID,
OrderID = ord.OrderID,
OrderDate = ord.OrderDate.Value,
ShipCountry = ord.ShipCountry
};
var ordrs = qry.ToList();
return View(ordrs);
}
and here is my class
public class OrdersModel
{
[Required]
[Display(Name = "OrderID")]
public int OrderID { get; set; }
[Required]
[Display(Name = "OrderDate")]
public DateTime OrderDate { get; set; }
[Required]
[Display(Name = "CustomerID")]
public string CustomerID { get; set; }
[Display(Name = "ShipCountry")]
public string ShipCountry { get; set; }
}
The
CustomerIDis not turning up because you’re not providing a type to yourIEnumerablecast..NET does the best it can and treats each item as an
object, which does not contain theCustomerIDproperty.EDIT:
Inspired by Jan’s comment, this is the way I’d actually go about it.
Create a better model, where Orders is a property of the view model.
Then in your controller:-
As Jan says, make sure the view is strongly-typed, and ready to accept OrdersListVM as its type.
You can check this by looking at the page directive in your .aspx page.
Finally, change your markup to:-
Everything will have the right type, and if you need to put anything else on your view apart from a bare list of orders, you have a container to place it in.