2012-05-17 8 views
5

Po prostu zacząłem robić MVC 4 i bardzo mi się to podobało, ale wpadam w kłopoty, kiedy jestem próbuje uzyskać moją bazę danych (tylko wpisy NAME i EMAIL), aby wyświetlić wszystkie wpisy w widoku indeksu. Pojawia się następujący błąd:MVC - Słownik wymaga elementu modelu typu "System.Collections.Generic.IEnumerable`1

The model item passed into the dictionary is of type 'System.Collections.Generic.List 1[MobileWebFormver2.Models.WebForm1]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable 1[MobileWebFormver2.Models.User]'.

Udało mi się połączyć program z bazą danych, ale prawie utknąłem tutaj. Zastanawiałem się, czy mogę uzyskać pomoc. Oto mój kod:

Class User

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.ComponentModel.DataAnnotations; 

namespace MobileWebFormver2.Models 
{ 
    public class User 
    { 
     [Required(ErrorMessage="Please enter name.")] 
     public string Name { get; set; } 
     [Required(ErrorMessage="Please enter email.")] 
     public string Email { get; set; } 
    } 
} 

HomeController (WebForm1 jest wpis w bazie danych, która zawiera nazwę i pole EMAIL)

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.Mvc; 
using MobileWebFormver2.Models; 
using System.Data.Entity; 

namespace MobileWebFormver2.Controllers 
{ 
    public class HomeController : Controller 
    { 
     DataClasses1DataContext db = new DataClasses1DataContext(); 

     public ActionResult Index() 
     { 
      ViewBag.Message = "This is the TourEast Holidays Mobile Index"; 

      return View(db.WebForm1s.ToList()); 
     } 
    } 
} 

Index

@model IEnumerable<MobileWebFormver2.Models.User> 

@{ 
    ViewBag.Title = "Home Page"; 
} 

@foreach (var item in Model) 
{ 
    <tr> 
     <td> 
     @Html.DisplayFor(modelItem => item.Name) 
     </td> 
     <td> 
     @Html.DisplayFor(modelItem => item.Email) 
     </td> 
    </tr> 
} 

EDYCJA: Odnosi się to do DataClasses1DataContext. Nie jestem pewien, jakie to będzie przydatne.

DataClasses1.cs

namespace MobileWebFormver2.Models 
{ 
    partial class DataClasses1DataContext 
    { 
    } 
} 

DataClasses1.designer.cs

#pragma warning disable 1591 
//------------------------------------------------------------------------------ 
// <auto-generated> 
//  This code was generated by a tool. 
//  Runtime Version:4.0.30319.269 
// 
//  Changes to this file may cause incorrect behavior and will be lost if 
//  the code is regenerated. 
// </auto-generated> 
//------------------------------------------------------------------------------ 

namespace MobileWebFormver2.Models 
{ 
using System.Data.Linq; 
using System.Data.Linq.Mapping; 
using System.Data; 
using System.Collections.Generic; 
using System.Reflection; 
using System.Linq; 
using System.Linq.Expressions; 
using System.ComponentModel; 
using System; 


[global::System.Data.Linq.Mapping.DatabaseAttribute(Name="MobileWebForm")] 
public partial class DataClasses1DataContext : System.Data.Linq.DataContext 
{ 

    private static System.Data.Linq.Mapping.MappingSource mappingSource = new AttributeMappingSource(); 

#region Extensibility Method Definitions 
partial void OnCreated(); 
partial void InsertWebForm1(WebForm1 instance); 
partial void UpdateWebForm1(WebForm1 instance); 
partial void DeleteWebForm1(WebForm1 instance); 
#endregion 

    public DataClasses1DataContext() : 
      base(global::System.Configuration.ConfigurationManager.ConnectionStrings["MobileWebFormConnectionString"].ConnectionString, mappingSource) 
    { 
     OnCreated(); 
    } 

    public DataClasses1DataContext(string connection) : 
      base(connection, mappingSource) 
    { 
     OnCreated(); 
    } 

    public DataClasses1DataContext(System.Data.IDbConnection connection) : 
      base(connection, mappingSource) 
    { 
     OnCreated(); 
    } 

    public DataClasses1DataContext(string connection, System.Data.Linq.Mapping.MappingSource mappingSource) : 
      base(connection, mappingSource) 
    { 
     OnCreated(); 
    } 

    public DataClasses1DataContext(System.Data.IDbConnection connection, System.Data.Linq.Mapping.MappingSource mappingSource) : 
      base(connection, mappingSource) 
    { 
     OnCreated(); 
    } 

    public System.Data.Linq.Table<WebForm1> WebForm1s 
    { 
     get 
     { 
      return this.GetTable<WebForm1>(); 
     } 
    } 
} 

[global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.WebForm1")] 
public partial class WebForm1 : INotifyPropertyChanging, INotifyPropertyChanged 
{ 

    private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty); 

    private string _Name; 

    private string _Email; 

#region Extensibility Method Definitions 
partial void OnLoaded(); 
partial void OnValidate(System.Data.Linq.ChangeAction action); 
partial void OnCreated(); 
partial void OnNameChanging(string value); 
partial void OnNameChanged(); 
partial void OnEmailChanging(string value); 
partial void OnEmailChanged(); 
#endregion 

    public WebForm1() 
    { 
     OnCreated(); 
    } 

    [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Name", DbType="NVarChar(50) NOT NULL", CanBeNull=false, IsPrimaryKey=true)] 
    public string Name 
    { 
     get 
     { 
      return this._Name; 
     } 
     set 
     { 
      if ((this._Name != value)) 
      { 
       this.OnNameChanging(value); 
       this.SendPropertyChanging(); 
       this._Name = value; 
       this.SendPropertyChanged("Name"); 
       this.OnNameChanged(); 
      } 
     } 
    } 

    [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Email", DbType="NVarChar(50) NOT NULL", CanBeNull=false)] 
    public string Email 
    { 
     get 
     { 
      return this._Email; 
     } 
     set 
     { 
      if ((this._Email != value)) 
      { 
       this.OnEmailChanging(value); 
       this.SendPropertyChanging(); 
       this._Email = value; 
       this.SendPropertyChanged("Email"); 
       this.OnEmailChanged(); 
      } 
     } 
    } 

    public event PropertyChangingEventHandler PropertyChanging; 

    public event PropertyChangedEventHandler PropertyChanged; 

    protected virtual void SendPropertyChanging() 
    { 
     if ((this.PropertyChanging != null)) 
     { 
      this.PropertyChanging(this, emptyChangingEventArgs); 
     } 
    } 

    protected virtual void SendPropertyChanged(String propertyName) 
    { 
     if ((this.PropertyChanged != null)) 
     { 
      this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); 
     } 
    } 
} 
} 
#pragma warning restore 1591' 

Spojrzałem na podobnych stanowiskach tutaj i wiem, że ma do czynienia z przechodzącą obiektu, ale widok oczekuje czegoś innego. Powiedziałbym jednak, że jestem programistą na bardzo początkującym poziomie i nie sądzę, żebym rozumiał większość z tego, co mówili. Zasadniczo poszedłem za kodem z witryny tutoriala MVC (Link) od Microsoft, jak wyświetlić bazę danych w indeksie, ale dostaję błąd. Wszelkie wskazówki będą mile widziane.

+0

Czy możesz pokazać swoją implementację DbContext? Będziesz potrzebował DbSet do zapytania. –

+0

Czy możesz podać mi instrukcje pokazujące implentację? Moje przeprosiny, jestem prawdziwym początkującym haha. Dzięki! –

+0

OK Poszedłem do moich modeli i istnieje DataClasses1.dbml. Kliknąłem go prawym przyciskiem myszy i kliknąłem kod widoku, a teraz jestem w DataClasses1.cs. w kodzie wszystko tam jest: MobileWebFormver2.Models namespace { częściowe klasa DataClasses1DataContext { } } @LeonCullens –

Odpowiedz

6

Problem polega na tym, że przekazujesz niewłaściwą rzecz do widoku. Przekazujesz kolekcję WebForm1, a nie User.

Edit - zmienić widok modelu to:

@model IEnumerable<MobileWebFormver2.Models.WebForm1> 

Edycja - nieco więcej wyjaśnień:

Na tej linii, tworzysz ActionResult i przekazując dane do modelu.

return View(db.WebForm1s.ToList()); 

Jednak db.WebForm1s jest zbiorem typu WebForm1.

Państwa zdaniem robisz silnie typami widoku kiedy zadeklarować model:

@model IEnumerable<MobileWebFormver2.Models.User> 

Widok oczekuje zbiór użytkowników, lecz przeszedł WebForm1 zamiast. Stąd błąd - musisz zdecydować, który z nich jest poprawny, kontroler przechodząc w WebForm1 lub widok i zmienić drugi, aby pasował.

+0

Zakładając, że DataClasses1DataContext zawiera DbSet zwane Użytkownicy oczywiście. –

+0

Rzeczywiście, po prostu zakładam, ponieważ nie pokazał on swojego kontekstu bazy danych, ale wydawał się rozsądnym założeniem. – Leniency

+0

Czy mogę zapytać, jak uzyskać DataClasses1DataContext zawierać DbSet ? Kiedy próbowałem dodać db.Users.ToList(), nie skompilowałem. Przykro mi, jeśli to głupie pytanie, jestem całkiem nowy w programowaniu, szczególnie obiektowym. Naprawdę doceniam pomoc :) –

Powiązane problemy