Mvc错误 - 需要类型为ienumerable的模型项 [英] Mvc error - requires model item of type ienumerable
本文介绍了Mvc错误 - 需要类型为ienumerable的模型项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是MVC和LinqToSql的新手。我正在尝试创建一个小应用程序,列出使用这两种技术的联系人。
我尝试过:
我的型号:
I'm new to both MVC and LinqToSql. I'm trying to create a small application that lists contacts using both technologies.
What I have tried:
My Model:
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 }
我的控制器:
My Controller:
public class ContactController : Controller
{
private static string conStr = ConfigurationManager.ConnectionStrings["conStr"].ConnectionString;
LinqToSqlDataContext db = new LinqToSqlDataContext(conStr);
// GET: Contacts
public ActionResult Index()
{
IList<Contact> contactList = new List<Contact>();
var listdata = (from c in db.Contacts select c).ToList();
foreach (var item in listdata)
{
contactList.Add(new Contact()
{
Id = item.Id,
Name = item.Name,
Age = item.Age,
Email = item.Email,
Phone = item.Phone,
Gender = item.Gender,
Address = item.Address
});
}
return View(contactList);
}
我的观点:
My View:
@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>
运行时我收到以下错误:
When I run this I get the following error:
The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[ContactsApp.Contact]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[ContactsApp.Models.Contact]'.
我很感激帮助理解我做错了什么。
谢谢。
I'd appreciate help in understanding exactly what I am doing wrong.
Thank you.
推荐答案
好吧,既然IList实现了IEnumerable,那你应该很好。
但是,你没有真正阅读错误信息。你显然有两个不同的Contact类。一次在名为ContactsApp
的名称空间中,另一名在名为ContactsApp.Models
的名称空间中。这两个是不可互换的。
您需要更改Razor代码中的@model
行或更改您要添加到列表中的哪个对象。当然,我不能告诉你要做哪一个。
Well, since IList implements IEnumerable, you should be good there.
But, you didn't really read the error message. You apparently have two different Contact classes. once in a namespace calledContactsApp
and the other in a namespace calledContactsApp.Models
. The two are not interchangeable.
You need to either change the@model
line in you Razor code or change which object you're adding to the list. Of course, I can't tell you which one to do.
这篇关于Mvc错误 - 需要类型为ienumerable的模型项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文