首页 > 解决方案 > MVC 错误 - 需要 IEnumerable 类型的模型项

问题描述

我是 MVC 和 LinqToSql 的新手。我正在尝试创建一个使用这两种技术列出联系人的小型应用程序。

我的模型:

public class Contact 
{
    [Key]
    public int Id { get; set; }
    [Required]
    public string Name { get; set; }
    [Range(18, 99)]
    public int? Age { get; set; }
    [EmailAddress]
    public string Email { get; set; }
    [Phone]
    public string Phone { get; set; }
    public Gender? Gender { get; set; }
    public string Address { get; set; }
}

public enum Gender { Male, Female }

我的控制器:

public class ContactController : Controller
{
    private string conStr = ConfigurationManager.ConnectionStrings["conStr"].ConnectionString;
    private LinqToSqlDataContext db;

     public ActionResult Index()
     {
        using (db = new LinqToSqlDataContext(conStr))
        {
            var contacts = (IEnumerable)(from c in db.Contacts select c);
            return View(contacts);
        }
    }

我的观点:

@model IEnumerable<ContactsApp.Models.Contact>

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Name)
        </th>
        ...
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Name)
        </td>
         ...          
    </tr>
}

</table>

当我运行它时,我收到以下错误:

传递到字典中的模型项的类型为“System.Data.Linq.DataQuery 1[ContactsApp.Contact]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable1[ContactsApp.Models.Contact]”。

我了解 View 需要一个 IEnumerable 参数。我将查询转换为 IEnumerable 但我仍然收到错误消息。

我很感激帮助我了解我到底做错了什么以及解决这个问题的最有效方法是什么。

标签: c#asp.net-mvclinq-to-sqlienumerable

解决方案


问题是您的查询返回IQueryable

(from c in db.Contacts select c) // <-- returns IQueryable

您需要将其转换为 List (这是一个IEnumerable

using (db = new LinqToSqlDataContext(conStr))
{
    var contacts = db.Contacts.ToList(); // <-- converts the result to List
    return View(contacts);
}

推荐阅读