c# - 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.IEnumerable
1[ContactsApp.Models.Contact]”。
我了解 View 需要一个 IEnumerable 参数。我将查询转换为 IEnumerable 但我仍然收到错误消息。
我很感激帮助我了解我到底做错了什么以及解决这个问题的最有效方法是什么。
解决方案
问题是您的查询返回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);
}
推荐阅读
- reactjs - 检查 `Formik` 的渲染方法
- node.js - 出现此错误时,PM2 不会重新启动 Node JS 应用程序
- azure-ad-b2c - 更改密码 Azure AD B2C
- api-platform.com - 如何在单一资源的 api-platform 中使用私有和公共路由
- jquery - 如何制作滑块Jquery的动画
- html - Angular:返回 URL 错误:在此服务器上找不到请求的 URL
- posix - 检查进程是否仍然存在
- react-native - React Native Build Error on IOS - typedef 用不同类型重新定义('uint8_t'(又名'unsigned char')与'enum clockid_t')
- python - 捕获和操作网络摄像头提要并将其公开为“虚拟网络摄像头” - 在 Python 中,在 Windows 上
- angular - 在 Angular 7 的 docx 库中显示图像