2012-05-17 6 views
5

Ho appena iniziato a fare MVC 4 e mi sono divertito un bel po', ma mi trovo nei guai quando sono cercando di ottenere il mio database (solo voci NAME e EMAIL) per mostrare tutte le sue voci nella vista indice. Viene visualizzato il seguente errore:MVC - Il dizionario richiede un modello del tipo '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]'.

Sono stato in grado di collegare il programma al database, ma sono praticamente bloccato qui. Mi stavo chiedendo se potevo ricevere aiuto. Qui è il mio codice:

User Class

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 è una voce di database, che contiene un nome e il campo E-MAIL)

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()); 
     } 
    } 
} 

Indice

@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> 
} 

MODIFICA: si riferisce a DataClasses1DataContext. Non sono sicuro di quanto utile sarà.

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' 

ho guardato i messaggi simili qui e so che ha a che fare con il passaggio di un oggetto, ma il la vista si aspetta qualcosa d'altro Comunque direi che sono un programmatore di livello da principiante e non credo di aver capito la maggior parte di quello che stavano dicendo. Fondamentalmente ho seguito il codice dal sito di tutorial MVC (Link) di Microsoft su come mostrare il tuo database nell'indice, ma sto ricevendo l'errore. Qualsiasi suggerimento sarebbe davvero apprezzato.

+0

Puoi mostrare la tua implementazione di DbContext? Avrai bisogno di un DbSet per eseguire una query. –

+0

Potete fornirmi le istruzioni su come mostrare l'impianto? Le mie scuse, sono un vero principiante haha. Grazie! –

+0

Ok, sono passato ai miei modelli e c'è un DataClasses1.dbml. Ho fatto clic con il tasto destro del mouse e ho fatto clic su Visualizza codice e ora sono in DataClasses1.cs. nel codice tutto quello che c'è è: MobileWebFormver2.Models namespace { classe parziale DataClasses1DataContext { }} @LeonCullens –

risposta

6

Il problema è che stai passando la cosa sbagliata nella vista. Stai passando una raccolta di WebForm1 e non di User.

Edit - Modificare il modello di vista a questo:

@model IEnumerable<MobileWebFormver2.Models.WebForm1> 

Modifica - un po 'più spiegazione:

Su questa linea, si sta creando l'ActionResult e passando nei dati per il modello.

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

Tuttavia, db.WebForm1s è una raccolta di tipo WebForm1.

Secondo lei, si stanno facendo una vista fortemente tipizzato quando si dichiara il modello:

@model IEnumerable<MobileWebFormver2.Models.User> 

La vista si aspetta un insieme di utenti, ma è passato WebForm1 invece. Da qui l'errore: devi decidere quale è corretto, il controller che passa in WebForm1 o la vista e cambiare l'altro in modo che corrisponda.

+0

Supponendo che DataClasses1DataContext contiene un DbSet chiamati gli utenti di corso. –

+0

In effetti, sto solo partendo dal presupposto che non ha mostrato il suo contesto di database, ma sembrava un'ipotesi ragionevole. – Leniency

+0

posso chiedere come si ottiene DataClasses1DataContext per contenere DbSet ? Quando ho provato ad aggiungere db.Users.ToList(), non è stato compilato. Mi dispiace se questa è una domanda stupida, sono abbastanza nuovo alla programmazione soprattutto orientata agli oggetti. Apprezzo molto l'aiuto :) –

Problemi correlati