asp.net-mvc MVC - 字典需要类型为“System.Collections.Generic.IEnumerable”1 的模型项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10628616/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 01:56:47  来源:igfitidea点击:

MVC - Dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1

asp.net-mvcrazor

提问by J-Y

I just started doing MVC 4 and I've been enjoying it quite a bit, but I'm running into trouble when I'm trying to get my database (just NAME and EMAIL entries) to show all its entries in the index view. I get the following error:

我刚刚开始使用 MVC 4 并且我一直很享受它,但是当我试图让我的数据库(只有 NAME 和 EMAIL 条目)在索引视图中显示其所有条目时遇到了麻烦。我收到以下错误:

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

传递到字典中的模型项的类型为 'System.Collections.Generic.List 1[MobileWebFormver2.Models.WebForm1]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable1[MobileWebFormver2.Models.User]'

I was able to connect the program to the database, but I'm pretty much stuck here. I was wondering if I could get some help. Here's my code:

我能够将程序连接到数据库,但我几乎卡在这里。我想知道我是否可以得到一些帮助。这是我的代码:

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 is a database entry, that contains a NAME and EMAIL field)

HomeController(WebForm1 是一个数据库条目,包含一个 NAME 和 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>
}

EDIT: This refers to DataClasses1DataContext. I'm not sure how useful this will be.

编辑:这是指 DataClasses1DataContext。我不确定这会有多大用处。

DataClasses1.cs

数据类1.cs

namespace MobileWebFormver2.Models
{
    partial class DataClasses1DataContext
    {
    }
}

DataClasses1.designer.cs

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'

I looked at similar posts here and I know it has to do with passing an object, but the view is expecting something else. However I would say I'm a very beginner level programmer and I don't think I understood most of what they were saying. I basically followed the code from the MVC tutorial site (Link) from Microsoft on how to show your database in the index, but I'm getting the error. Any guidance would be greatly appreciated.

我在这里查看了类似的帖子,我知道它与传递对象有关,但该视图期待其他内容。但是我会说我是一个非常初级的程序员,我认为我没有理解他们所说的大部分内容。我基本上遵循了来自 Microsoft的 MVC 教程站点 ( Link) 中有关如何在索引中显示您的数据库的代码,但我收到了错误消息。任何指导将不胜感激。

回答by Leniency

The problem is that you're passing the wrong thing into the view. You're passing a collection of WebForm1's, not User's.

问题是你将错误的东西传递到视图中。您正在传递WebForm1's的集合,而不是User's。

Edit - Change your view model to this:

编辑 - 将您的视图模型更改为:

@model IEnumerable<MobileWebFormver2.Models.WebForm1>

Edit - a bit more explanation:

编辑 - 多一点解释:

On this line, you are creating the ActionResult and passing in the data for the model.

在这一行中,您正在创建 ActionResult 并传入模型的数据。

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

However, db.WebForm1s is a collection of type WebForm1.

但是, db.WebForm1s 是类型的集合WebForm1

In your view, you are making a strongly typed view when you declare the model:

在您的视图中,当您声明模型时,您正在创建一个强类型视图:

@model IEnumerable<MobileWebFormver2.Models.User>

The view expects a collection of users, but is passed WebForm1 instead. Hence the error - you have to decide which one is correct, the controller passing in WebForm1, or the view, and change the other to match.

该视图需要一组用户,但改为传递 WebForm1。因此出现错误 - 您必须决定哪个是正确的,是传入 WebForm1 的控制器还是视图,然后更改另一个以匹配。