2015-06-17 253 views
0

我試圖綁定劍道Grid.but它顯示我以下錯誤劍道UI網格結合

傳遞到詞典中的模型項的類型爲「System.Data.Entity.DbSet 1[KendoApp.Product]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable 1 [KendoApp .Models.ProductModels]」。

我查看

@model IEnumerable<KendoApp.Models.ProductModels> 

@(Html.Kendo().Grid(Model) 
.Name("Grid") 
    .Columns(columns => 
    { 
     columns.Bound(p => p.ProductID); 
     columns.Bound(p => p.ProductName); 
     columns.Bound(p => p.UnitPrice); 
     columns.Bound(p => p.UnitsInStock); 
    }).Pageable() 
) 

我的控制器

public ActionResult KendoGrid() 
    { 

     //IEnumerable<Product> products = new northwindEntities().Products; 

     var products = new northwindEntities().Products; 
     ViewBag.Products = products; 
     return View(products); 

產品型號

public class ProductModels 
{ 
    public int ProductID { get; set; } 
    public string ProductName { get; set; } 
    public Nullable<int> SupplierID { get; set; } 
    public Nullable<int> CategoryID { get; set; } 
    public string QuantityPerUnit { get; set; } 
    public Nullable<decimal> UnitPrice { get; set; } 
    public Nullable<short> UnitsInStock { get; set; } 
    public Nullable<short> UnitsOnOrder { get; set; } 
    public Nullable<short> ReorderLevel { get; set; } 
    public bool Discontinued { get; set; } 
} 
    } 

什麼錯誤?如何解決這個問題?

回答

2

請試試這個,

您的看法:

@(Html.Kendo().Grid<KendoApp.Models.ProductModels>() 
    .Name("grid") 
    .Columns(columns => 
    { 
     columns.Bound(p => p.ProductID); 
     columns.Bound(p => p.ProductName); 
     columns.Bound(p => p.UnitPrice); 
     columns.Bound(p => p.UnitsInStock); 
    }) 
    .Pageable() 
    .DataSource(dataSource => dataSource 
     .Ajax() 
     .Read(read => read.Action("ProductsRead", "YourControllerName")) 
    ) 
) 

您的控制器操作:

public JsonResult ProductsRead([DataSourceRequest] DataSourceRequest request) 
{ 
    var products = new northwindEntities().Products 
     .Select(p => new ProductModels { 
      ProductID = p.ProductID, 
      ProductName = p.ProductName, 
      UnitPrice = p.UnitPrice, 
      UnitsInStock = p.UnitInStock 
     }) 
     .AsQueryable(); 

    return Json(products.ToDataSourceResult(request)); 
} 

public ActionResult KendoGrid() 
{ 
    return View(); 
} 
0

您接受到你的觀點,並與網格結合的類型,是KendoApp.Models.ProductModels的集合。從控制器傳遞的是KendoApp.Product類型的實體的集合。它們不被視爲相同的類型(即使這些類中的所有屬性都是這樣),這就是爲什麼你會得到錯誤。

您需要做的是將KendoApp.Product實體轉換爲控制器中的ProductModels類的新IEnumerable集合。喜歡的東西:

var products = new northwindEntities().Products.Select 
    (x => new KendoApp.Models.ProductModels 
     { 
      ProductID = x.ProductID, 
      ProductName = x.ProductName, 
      ... 
      Discontinued = x.Discontinued 
     } 
    ).ToList(); 

var這個產品現在是IEnumerable類型< KendoApp.Models.ProductModels>將由您的觀點被接受。