2012-09-22 23 views
4

我会说一点英语。我试着问我的问题。通过IEnumerable变量在ASP中查看MVC

我有一个模型。它的名字Product.cs

Product 
    { 
    public int TypeId { get; set; }/*these are at the same time field of Type Table*/ 
    public string TypeName { get; set; } 

    public int TradeMarkId { get; set; }/*at the same time field of TradeMark Table*/ 
    public string TradeMarkName { get; set; } 

    public int ProductId { get; set; }/*at the same time field of TProduct Table*/ 
    public string ProductName { get; set; } 
    public int TId { get; set; } 
    public int TMId { get; set; } 

    public List<TypeProduct> typeList { get; set; } 
    } 

我控制器页面

My controller 
    [HttpGet] 
    public ActionResult TradeMarkProduckAdd() 
    { 
    Product product = new Product(); 
    TypeList typeList = new TypeList(); 
    product = typeList.TypeListOf(product); 
    return View(product);//"This doesn't work"    
    } 

它说一个类型的错误 传递到字典的模型项的类型为“TypeMark.Models.Product”,但这个字典要求一个'System.Collections.Generic.IEnumerable`1 [TypeMark.Models.Product]'类型的模型项目。

当我得到这个错误我改变了返回查看(产品);return View((IEnumerable)product);但它没有再次工作。

视图页面

@using TypeTradeMark.Models 
    @model IEnumerable<Product> 
    @using (Html.BeginForm("AddProduct", "Home", FormMethod.Post)) 
    { 
     @foreach(var item in Model as List<Product>) 
     {        
     @item.ProductName 
     @item.??//checkbox for every record  
     @item.??//dropdownlist for trademarks  
     }  
    } 

TYPELIST类

TypeList class 

    public class TypeList 
    { 
     VtDataContext Vt = new VtDataContext(); 
     public Product TypeListOf(Product typeListOf) 
     {   
     var query = (from c in Vt.Types select c); 
     typeListOf.typeList=new List<Type>(query.ToList()); 
     return typeListof; 
     } 
    } 

我的表

Type : TypeId, TypeName 
    TradeMark : TradeMarkId,TradeMarkName 
    TProduct : ProductId,ProductName,TId,TMId//TId relation with TypeId, TMId relation with TradeMarkId 

我想不出你能帮我解决这个问题?谢谢

+0

这是一些教程吗? – Grixxly

+0

你的模型有点奇怪......你如何创建数据库?你必须支持已经存在的分贝,还是你自己创建它? – Dmytro

+0

我创建数据库。这是错的吗? – sedat

回答

1

您查看期望列表Product类型对象,请参阅(@model IEnumerable<Product>)。

尝试使用这样的:

return View(new List<Product> { product, product2 }) 
+0

谢谢,但有一个地方我不明白。返回查看(产品);产品已经是一个列表(我认为)不是吗?我的列表(意味着产品)来自数据库。所以我怎样才能在返回视图中创建一个新列表 – sedat

+0

您查看的是强类型的(您使用@model来做到这一点)。如果您希望您的视图只接受一个产品,只需放弃IEnumerable,请使用'@model Product' –

0

我相信你需要创建一个接口,像这样:

public interface IProduct 
{ 
    IEnumerable<Product> Products { get; } 
} 

更改您的控制器使用该IEnumerable接口而不是类产品。

0

在您的视图中,您声明了@model IEnumerable,这意味着此视图强类型为Product类型的Enumeration,并且您的视图将始终期望typ类型的枚举。你在这里得到的错误是因为你正在传递一个单独的Product对象,它与View类型不匹配。

如果您想坚持使用IEnumeratble<product>,您可能需要在Controller或TypeListOf()方法中创建产品列表并将其传递给View。