How do I return multiple columns to a View?
I want to return to my view Product information(Name and Cost) and am running into the following error in my View code's foreach statement: Cannot implicitly convert type 'ProductApp.Models.Product' to 'System.Collections.IEnumerable'. An ex开发者_运维百科plicit conversion exists (are you missing a cast?)
I seem to be missing something stupid simple. Can anyone help me correct this?
Repository Code:
public class ProductRepository
{
DatabaseEntities db = new DatabaseEntities();
public IQueryable<Product> FindAllProducts()
{
return db.Products;
}
public Product GetProductInfo(int id)
{
return db.Product.FirstOrDefault(p => p.Product_ID == id);
}
}
Controller Code:
public ActionResult Index(int id)
{
Product product = productRepository.GetProductInfo(id);
return View("Index", product);
}
View Code:
<ul>
<% foreach (var product in Model)
{ %>
<li>
<%: product.Product_Name%>
which costs
<%: product.Product_Cost%>
is available.
</li>
<% } %>
</ul>
In your view, look at the Model type. Your first line in the view will tell you what type the View expects:
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<myApp.Model.Product>" %>
The Inherits
portion should tell you what type you expect. In the above example it expects a single Product
type. This needs to match the type of the object that you pass into the View() method in your controller.
Your view probably has an inherit type that is something like this"
...Inherits="System.Web.Mvc.ViewPage<List<myApp.Model.Product>>"...
So you should make sure to return the list of items from your Controller.
You're looping over a single instance of a Product. You're passing to the view what gets returned from GetProductInfo, which is not a collection of products.
精彩评论