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);
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.