【问题标题】:MVC Error - Requires a model item of type IEnumerableMVC 错误 - 需要 IEnumerable 类型的模型项
【发布时间】:2019-09-10 01:24:28
【问题描述】:

我是 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.DataQuery1[ContactsApp.Contact]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable1[ContactsApp.Models.Contact]'。

我了解 View 需要一个 IEnumerable 参数。我将查询转换为 IEnumerable,但仍然出现错误。

如果能帮助我了解我到底做错了什么以及解决此问题的最有效方法是什么,我将不胜感激。

【问题讨论】:

    标签: c# asp.net-mvc linq-to-sql ienumerable


    【解决方案1】:

    问题是您的查询返回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);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-11-26
      • 2023-03-25
      • 2011-09-06
      • 2020-03-14
      • 1970-01-01
      • 1970-01-01
      • 2015-02-07
      相关资源
      最近更新 更多