renderpartial with null model gets passed the wron

2019-01-03 21:44发布

I have a page:

<%@ Page Inherits="System.Web.Mvc.View<DTOSearchResults>" %>

And on it, the following:

<% Html.RenderPartial("TaskList", Model.Tasks); %>

Here is the DTO object:

public class DTOSearchResults
{
    public string SearchTerm { get; set; }
    public IEnumerable<Task> Tasks { get; set; }

and here is the partial:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<IEnumerable<Task>>" %>

When Model.Tasks is not null, everything works fine. However when its null I get:

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); %>

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?

7条回答
霸刀☆藐视天下
2楼-- · 2019-01-03 22:19

If you do not want to loose your previous ViewData in the partial view, you could try:

<% Html.RenderPartial("TaskList", Model.Tasks, new ViewDataDictionary(ViewData){Model = null});%>
查看更多
登录 后发表回答