C# 传递到字典中的模型项的类型为“mvc.Models.ModelA”,但该字典需要类型为“mvc.Models.ModelB”的模型项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2315129/
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-08-07 01:20:53  来源:igfitidea点击:

The model item passed into the dictionary is of type ‘mvc.Models.ModelA’ but this dictionary requires a model item of type ‘mvc.Models.ModelB‘

c#asp.net.netasp.net-mvcbuild-process

提问by Mathias F

I have this annoying mistake in some of my builds.

在我的一些构建中,我有这个烦人的错误。

There is no error in the project, because if I build again, then the problem disappears. The message only appears, when the site is deployed to a Windows 2008 Server.

项目中没有错误,因为如果我再次构建,那么问题就会消失。该消息仅在站点部署到 Windows 2008 Server 时出现。

I first thought that it might be an issue with temporary files, but thats not the case. I deployed the build to a different web and the error still appears.

我首先认为这可能是临时文件的问题,但事实并非如此。我将构建部署到不同的网站,但错误仍然出现。

The error appears on random actions of the site. Most of the time builds are ok, but each 3rd or 4th build produces runtime errors.

该错误出现在站点的随机操作上。大多数情况下构建都可以,但是每个第 3 次或第 4 次构建都会产生运行时错误。

I build using a WebdeploymentProject in release mode. Views are precompiled.

我在发布模式下使用 WebdeploymentProject 进行构建。视图是预编译的。

It's not In ASP.NET MVC I encounter an incorrect type error when rendering a page with the correct typed object, because views have totally different names.

这不是在 ASP.NET MVC 中,我在呈现具有正确类型对象的页面时遇到错误类型错误,因为视图具有完全不同的名称。

How I can debug this problem or how I can get help for this?

我如何调试这个问题或者我如何获得帮助?

Here is my WebDeploymentProject

这是我的 WebDeploymentProject

    <!-- 
      Microsoft Visual Studio 2008 Web Deployment Project 
      http://go.microsoft.com/fwlink/?LinkID=104956

    -->
    <Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
      <PropertyGroup>
        <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
        <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
        <ProductVersion>9.0.21022</ProductVersion>
        <SchemaVersion>2.0</SchemaVersion>
        <ProjectGuid>{E5E14CEB-0BCD-4203-9A5A-34ABA9C717EA}</ProjectGuid>
        <SourceWebPhysicalPath>..\B2CWeb</SourceWebPhysicalPath>
        <SourceWebProject>{3E632DB6-6DB3-4BD0-8CCA-12DE67165B48}|B2CWeb\B2CWeb.csproj</SourceWebProject>
        <SourceWebVirtualPath>/B2CWeb.csproj</SourceWebVirtualPath>
        <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
      </PropertyGroup>
      <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
        <DebugSymbols>true</DebugSymbols>
        <OutputPath>.\Debug</OutputPath>
        <EnableUpdateable>false</EnableUpdateable>
        <UseMerge>true</UseMerge>
        <SingleAssemblyName>B2CWeb_Build</SingleAssemblyName>
      </PropertyGroup>
      <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
        <DebugSymbols>false</DebugSymbols>
        <OutputPath>..\B2CWeb_Deploy\</OutputPath>
        <EnableUpdateable>false</EnableUpdateable>
        <UseMerge>true</UseMerge>
        <SingleAssemblyName>B2C_Web</SingleAssemblyName>
        <ContentAssemblyName>
        </ContentAssemblyName>
        <DeleteAppCodeCompiledFiles>false</DeleteAppCodeCompiledFiles>
      </PropertyGroup>
      <ItemGroup>
      </ItemGroup>
      <Import Project="$(MSBuildExtensionsPath)\Microsoft\WebDeployment\v9.0\Microsoft.WebDeployment.targets" />
      <!-- To modify your build process, add your task inside one of the targets below and uncomment it. 
           Other similar extension points exist, see Microsoft.WebDeployment.targets.
      <Target Name="BeforeBuild">
      </Target>
      <Target Name="BeforeMerge">
      </Target>
      <Target Name="AfterMerge">
      </Target>
      <Target Name="AfterBuild">
      </Target>
      -->
    </Project>

EDIT

编辑

After some months this problem disapeared. I haven't had problems for over 1 year now. I guess the issue will strike again when nobody expects it.

几个月后,这个问题消失了。我现在已经1年多了没有问题。我想这个问题会在没人预料到的时候再次出现。

EDIT 2

编辑 2

… for over 2 years now. I am such a lucky dude!

…… 2 年多了。我真是个幸运的家伙!

EDIT 3

编辑 3

I just read an article on MSDN, and it sounds like the problem I had. I have debugging disabled, but still the compilation was "sometimes wrong". The behaviour of the old provider could be the issue. But this is just guessing.

我刚刚在 MSDN 上阅读了一篇文章,这听起来像是我遇到的问题。我禁用了调试,但编译仍然“有时是错误的”。旧提供程序的行为可能是问题所在。但这只是猜测。

Very large pages containing long spans of HTML with no server blocks (e.g. <%= %>) can cause a stack overflow when debug compilation is enabled that will crash the application. Note that in our testing it's taken a page that's ~4x as large one that would've produced a similar issue in the old provider, but in this case it crashes the entire application, whereas with the old provider it just fails the offending page

当启用调试编译时,包含长跨度 HTML 且没有服务器块(例如 <%= %>)的非常大的页面会导致堆栈溢出,从而使应用程序崩溃。请注意,在我们的测试中,它采用了一个大约 4 倍大的页面,这会在旧提供程序中产生类似的问题,但在这种情况下,它会使整个应用程序崩溃,而对于旧提供程序,它只会使违规页面失败

回答by svinto

Do the build trigger any warnings or errors at all?

构建是否会触发任何警告或错误?

Do you have your dependencies set up correctly? Eg. views depending on models. Build figures out in what order to compile things by looking at the dependencies specified. Eg. if you change a model and the view is compiled before the model you get into trouble...

您是否正确设置了依赖项?例如。视图取决于模型。Build 通过查看指定的依赖关系来确定编译的顺序。例如。如果您更改模型并且视图在模型之前编译,您会遇到麻烦......

Do this disappear if you don't compile views?

如果您不编译视图,这会消失吗?

Also do your views inherit System.Web.Mvc.ViewPageor System.Web.Mvc.ViewPage<T>where T is your model?

您的视图是否继承System.Web.Mvc.ViewPageSystem.Web.Mvc.ViewPage<T>T 是您的模型?

回答by Rune

Are you absolutelysure that this has nothing to do with the data being passed to the view? Are you performing a full rebuild each time?

绝对肯定这无关的数据传递到视图?您是否每次都执行完全重建?

These errors typically occur because a partial view tries to use the view model passed to the ViewPage when the view model passed to the partial view is null. I realize that you are implying that the error is somehow caused by the build process, but I don't see how that would be possible. Could it be that the deployed site uses a different database than the site you run on your development machine, and could the data (or lack of data) in that database be the cause of the problem?

这些错误的发生通常是因为当传递给分部视图的视图模型为空时,分部视图尝试使用传递给 ViewPage 的视图模型。我意识到您在暗示错误是由构建过程引起的,但我不知道这怎么可能。可能是部署的站点使用的数据库与您在开发机器上运行的站点不同,并且该数据库中的数据(或缺少数据)是否是问题的原因?

回答by Neil T.

This error can occur (and does) when there is a mismatch between the data that the controller action method is supplying to the view and the type of data the view is expecting. This will not normally show up as a build error, even with precompiled views.

当控制器操作方法提供给视图的数据与视图期望的数据类型不匹配时,会发生(并且确实)此错误。即使使用预编译视图,这通常也不会显示为构建错误。

For example, if I have a method...

例如,如果我有一个方法...

public ActionResult Create()
{
    // Do something
    return View(new CustomerCreateViewModel());
}

...and a Create view with a Page attribute...

...和具有 Page 属性的创建视图...

<%@ Page ... Inherits="System.Web.Mvc.ViewPage<CustomerDetailsViewModel>" %>

...this will compile and build without error. However, when I call the Create action, I'm going to get a yellow screen, because the Create action method is throwing data of one type and the view is expecting data of a different type. You might want to verify that your types are matching...

...这将编译和构建没有错误。但是,当我调用 Create 操作时,我将得到一个黄色屏幕,因为 Create 操作方法正在抛出一种类型的数据,而视图正在等待不同类型的数据。您可能想验证您的类型是否匹配...

回答by Maslow

Even if the types match, you can get this error when a null is passed to a partial view.

即使类型匹配,当 null 传递给局部视图时,您也会收到此错误。

You can fix this by calling RenderPartialwith an empty ViewDataDictionarylike this:

您可以通过像这样调用RenderPartial一个空来解决这个ViewDataDictionary问题:

helper.RenderPartial("~/Views/Player/PlayerName.ascx", player, new ViewDataDictionary());

For reference, I found this solution at:
renderpartial with null model gets passed the wrong type

作为参考,我在以下位置找到了这个解决方案:
renderpartial with null 模型得到了错误的类型

回答by Siva Gopal

Before assigning the model to the usercontrol from your view, instantiate that particular object in the constructor of the Model/Entity.

在从您的视图将模型分配给用户控件之前,请在模型/实体的构造函数中实例化该特定对象。

Example:

例子:

 public class MainEntity
 {
    public SubEntity AssociatedEntity;

    public MainEntity()
    {
        // This is where the instantiation happen.
        AssociatedEntity = new SubEntity(); 
    }
 }

 public class SubEntity
 {
    public string property1;
 }

Your View Page :

您的查看页面:

<%@ Page Title="" Language="C#" 
    MasterPageFile="~/Views/Shared/Site.Master" 
    Inherits="System.Web.Mvc.ViewPage<MyNamespace.Models.MainEntity>" %>
....
<%Html.RenderPartial("ucMyUserControl",Model.AssociatedEntity);
....

Your User Control:

您的用户控制:

<%@ Control Language="C#" 
    Inherits="System.Web.Mvc.ViewUserControl<MyNamespace.Models.SubEntity>" %>
....
<%Html.TextBoxFor(m=>m.Property1);

回答by Andrei

ASP.NET MVC Partials

ASP.NET MVC 部分

NULL model was passed!!!

NULL 模型通过!!!

@Html.Partial("PartialView", model: Model)

回答by cat5dev

If you have an overriding Viewsfolder, where multiple partials of the same name exist (one overriding another with the same name), be sure to update the Model type on each view or you might receive this error.

如果您有一个覆盖Views文件夹,其中存在多个同名部分(一个覆盖另一个具有相同名称的部分),请确保更新每个视图上的模型类型,否则您可能会收到此错误。

回答by Enrique Zavaleta

I had the following error message

我收到以下错误消息

The model item passed into the dictionary is of type 'System.Linq.Enumerable+WhereSelectListIterator2[MyProject.Models.A,MyProject.Models.B]', but this dictionary requires a model item of type 'System.Collections.Generic.List1[MyProject.Models.B]'.

传递到字典中的模型项的类型为“System.Linq.Enumerable+WhereSelectListIterator2[MyProject.Models.A,MyProject.Models.B]”,但此字典需要类型为“System.Collections.Generic.List1”的模型项[MyProject.Models.B]'。

with the following code

使用以下代码

IEnumerable<B> list_B;
...
IEnumerable<A> list_A = Repo.GetListOfType_A();
list_B = list_A.Select(x => new B { Number = x.Number, Name = x.Name });
...
return View(list_B);

and I have no idea what was the type

我不知道是什么类型

System.Linq.Enumerable+WhereSelectListIterator2[MyProject.Models.A,MyProject.Models.B]

System.Linq.Enumerable+WhereSelectListIterator2[MyProject.Models.A,MyProject.Models.B]

anyway, the error goes away when I add a .ToList()at the end

无论如何,当我.ToList()在最后添加 a 时错误消失了

IEnumerable<B> list_B;
...
IEnumerable<A>list_A = Repo.GetListOfType_A();
list_B = list_A.Select(x => new B { Number = x.Number, Name = x.Name }).ToList(); // here
...
return View(list_B);

Hope it helps someone else

希望它可以帮助别人

回答by danielc

For me this was caused by a silly cut and paste error in my context. I was getting this error on my Contact index.

对我来说,这是由我的上下文中愚蠢的剪切和粘贴错误引起的。我在我的联系人索引中收到此错误。

    public DbSet<Customer> Customer { get; set; }
    public DbSet<Customer> Contact { get; set; }
    // Note this ^^^^^^^^ should have been Contact

It compiled okay, but gave me the error when trying to render the view.

它编译没问题,但是在尝试渲染视图时给了我错误。

(Adding this as something else for future people looking for solutions to try.)

(将其添加为其他内容,供未来寻找解决方案的人尝试。)

回答by Hallonq

I got this error while using Episerver. I simply changed the return statement in the controller from return View();

使用 Episerver 时出现此错误。我只是将控制器中的 return 语句从return View();

to

return PartialView();

return PartialView();