带有 null 模型的 renderpartial 传递了错误的类型 [英] renderpartial with null model gets passed the wrong type
问题描述
我有一个页面:
<%@ Page Inherits="System.Web.Mvc.View<DTOSearchResults>" %>
还有以下内容:
<% Html.RenderPartial("TaskList", Model.Tasks); %>
这是 DTO 对象:
public class DTOSearchResults
{
public string SearchTerm { get; set; }
public IEnumerable<Task> Tasks { get; set; }
这里是部分:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<IEnumerable<Task>>" %>
当 Model.Tasks 不为空时,一切正常.但是,当它为空时,我得到:
When Model.Tasks is not null, everything works fine. However when its null I get:
传入字典的模型项是类型'DTOSearchResults' 但此字典需要类型为模型项'System.Collections.Generic.IEnumerable`1[任务]'.
The model item passed into the dictionary is of type 'DTOSearchResults' but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[Task]'.
我想它一定不知道使用哪个重载,所以我这样做(见下文)是为了明确,但我仍然遇到同样的问题!
I figured it must not know which overload to use, so I did this (see below) to be explicit, but I still get the same issue!
<% Html.RenderPartial("TaskList", (object)Model.Tasks, null); %>
我知道我可以通过检查 null 或什至不传递 null 来解决这个问题,但这不是重点.为什么会发生这种情况?
I know I can work around this by checking for null, or not even passing null, but that's not the point. Why is this happening?
推荐答案
Andrew 我认为您遇到的问题是 RenderPartial 方法在您传递模型时使用调用(视图)的模型到局部视图的结果为空.. 你可以通过执行以下操作来解决这种奇怪的行为:
Andrew I think the problem you are getting is a result of the RenderPartial method using the calling (view)'s model to the partial view when the model you pass is null.. you can get around this odd behavior by doing:
<% Html.RenderPartial("TaskList", Model.Tasks, new ViewDataDictionary()); %>
这有帮助吗?
这篇关于带有 null 模型的 renderpartial 传递了错误的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!