2013-04-22 204 views
1

我是ASP.NET MVC的初学者。我在尝试从数据库检索记录时遇到错误。检索记录时出错

'System.Collections.Generic.List' 不包含定义 '类别名称'

的LINQ to SQL类: enter image description here

型号:

namespace MvcApplication1.Models 
{ 
    public class CategoryRepository 
    { 
     private BusDataClassesDataContext dc = new BusDataClassesDataContext(); 

     public List<tblCategory> GetAllCategory() 
     { 
      return dc.tblCategories.ToList(); 
     } 
    } 
} 

控制器:

public class CategoryController : Controller 
{ 
     // 
     // GET: /Category/ 
     CategoryRepository cat = new CategoryRepository(); 

     public ActionResult ViewCategory() 
     { 
      var category = cat.GetAllCategory().ToList(); 
      return View("ViewCategory", category); 
     } 

    } 

查看:

<p> 
Category Name:<%=Html.Encode(Model.CategoryName)%> 
</p> 
<p> 
Description:<%= Html.Encode(Model.Description)%> 
</p> 

UPDATE:

enter image description here

+0

@ chamara-难道我的解决方案帮助您解决问题? – PSL 2013-04-22 04:04:44

回答

2

你传入List<tblCategory>的视图。因此Model这里将是generic list。这是为什么reaons你所得到的错误信息: -

'System.Collections.Generic.List' does not contain a definition for 'CategoryName'

你打算通过tblCategory要不你打算迭代以为模型去每个tblCategory?

你可以做这样

<% foreach(var category in Model) 
{%> 
<p> 
Category Name:<%=Html.Encode(category.CategoryName)%> 
</p> 
<p> 
Description:<%= Html.Encode(category.Description)%> 
</p> 
<% } %> 

在一点点不同的音符。 您已经在方法中将类型返回为GenericList。

public List<tblCategory> GetAllCategory() 
     { 
      return dc.tblCategories.ToList(); 
     } 

您不需要再次执行含糊的.ToList()转换。

var category = cat.GetAllCategory().ToList(); 
+0

我试图遍历tblCategory中的记录并在视图上显示 – chamara 2013-04-22 03:55:46

+0

这里发布的代码是否来自ViewCategory视图? – PSL 2013-04-22 03:56:31

+0

是的,它来自ViewCategory视图。尝试解决问题时出现错误。请参阅更新 – chamara 2013-04-22 04:07:18

2

使用该::

<% foreach (var category in Model)

的Ruther比::

@foreach (var category in Model)

视图

喜欢这个

<% foreach (var category in Model) 
    { %> 
<p> 
    Category Name :<%=Html.Encode(category.CategoryName)%></p> 
<p> 
    Description :<%=Html.Encode(category.Description)%></p> 
<% } %> 
+1

+1纠正语法... – PSL 2013-04-22 05:37:10