MVC模型类型不匹配错误:Gallery传参至_Pagination视图报错
问题:Partial视图模型类型不匹配错误
传入字典的模型项类型为'PageContent.Models.Gallery',但该字典要求模型项类型为'Base.Models.Pagination'。
我在_GalleryImages.cshtml视图中遇到上述错误,尝试过直接传递Model.Pagination,也试过把它赋值给变量后传给_Pagination.cshtml视图,但都没解决问题。相关代码如下:
Gallery.cshtml
@using PageContent.Models @model Gallery <section> . . . @Html.Partial("~/Views/_GalleryImages.cshtml", Model) </section>
_GalleryImages.cshtml
@using PageContent.Models @using Base.Models @model Gallery @{ Pagination pagination = Model != null ? Model.Pagination : null; } <section> . . . @Html.Partial("~/Views/_Pagination.cshtml", pagination) </section>
_Pagination.cshtml
@using Base.Models @model Pagination <section> . . . </section>
Gallery.cs
namespace PageContent.Models { using Base.Models; public class Gallery { public Pagination Pagination {get; set;} } }
Pagination.cs
namespace Base.Models { public class Pagination { } }
解决方法
问题根源是当传递给Partial视图的模型为null时,ASP.NET MVC会自动使用父视图的模型(也就是Gallery实例)来替代,这就导致了类型不匹配。
初始化Pagination实例:在控制器构造Gallery模型时,必须实例化Pagination属性,不能让它为null:
var gallery = new Gallery { Pagination = new Pagination() // 关键:实例化子属性 }; return View(gallery);强制传递空安全模型:如果无法保证Pagination一定不为null,可以在传递时用空合并运算符,显式传入一个空的Pagination实例,避免MVC fallback到父模型:
@Html.Partial("~/Views/_Pagination.cshtml", Model?.Pagination ?? new Pagination())
内容的提问来源于stack exchange,提问作者sukesh
相关产品推荐
相关产品推荐

