该错误意味着您正在导航到一个其模型被声明为typeof的视图
Foo(通过使用
@modelFoo),但实际上向它传递了一个typeof的模型
Bar(请注意,使用术语 字典
是因为模型是通过传递给该视图的
ViewDataDictionary) 。
该错误可能是由于
将错误的模型从控制器方法传递到视图(或局部视图)
常见的示例包括使用创建匿名对象(或匿名对象集合)的查询并将其传递给视图
var model = db.Foos.Select(x => new{ ID = x.ID, Name = x.Name};return View(model); // passes an anonymous object to a view declared with @model Foo或将一组对象传递给需要单个对象的视图
var model = db.Foos.Where(x => x.ID == id);return View(model); // passes IEnumerable<Foo> to a view declared with @model Foo
通过在控制器中显式声明模型类型以匹配视图中的模型,而不是使用,可以在编译时轻松识别错误
var。
将错误的模型从视图传递到局部视图
给定以下模型
public class Foo{ public Bar MyBar { get; set; }}和用声明的主视图和用声明
@model Foo的局部视图
@model Bar,然后
Foo model = db.Foos.Where(x => x.ID == id).Include(x => x.Bar).FirstOrDefault();return View(model);
将正确的模型返回到主视图。但是,如果视图包含
@Html.Partial("_Bar") // or @{ Html.RenderPartial("_Bar"); }默认情况下,传递给部分视图的模型是在主视图中声明的模型,您需要使用
@Html.Partial("_Bar", Model.MyBar) // or @{ Html.RenderPartial("_Bar", Model.MyBar); }将实例传递
Bar给局部视图。还要注意,如果
MyBaris 的值
null(尚未初始化),则默认情况下
Foo将传递给part,在这种情况下,需要
@Html.Partial("_Bar", new Bar())在布局中声明模型
如果布局文件包含模型声明,则使用该布局的所有视图都必须声明相同的模型或从该模型派生的模型。
如果要在布局中包含单独模型的html,请在布局中使用
@Html.Action(...)调用
[ChildActionOnly]方法来初始化该模型并返回其局部视图。



