【发布时间】: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.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-mvc linq-to-sql ienumerable