2012-09-22 24 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。