1

I have a composite ViewModel as below:

public class HomeListViewModel  
{
    public HomeSearchRequestViewModel SearchRequest { get; set; }

    public List<BasicAdSummaryViewModel> AdSummayResults { get; set; }
}

In my View, I want to render 2 PartialViews as below:

@model MyNameSpace.HomeListViewModel
<div>
   @Html.Partial("_SearchRequest", Model.SearchRequest)
   @Html.Partial("_AdSummary", Model.AdSummayResults)
</div>

This is my _SearchRequest PartialView

@model MyNameSpace.HomeSearchRequestViewModel
<div>
        @Html.EditorFor(m => m.Keyword, new { htmlAttributes = new { @class = "form-control", @type = "text"} })
</div>

And this is my _AdSummary PartialView:

@model IEnumerable<MyNameSpace.BasicAdSummaryViewModel>
@foreach (var item in Model) {
<tr>
    <td>
        @Html.DisplayFor(modelItem => item.Title)
    </td>
</tr>

The first PartialView renders fine, But I get the this error on second PartialView:

System.InvalidOperationException: 'The model item passed into the dictionary is of type 'MyNameSpace.HomeListViewModel', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[MyNameSpace.BasicAdSummaryViewModel]'.'

I only get this error while rendering a partial view with a List view model...

Hooman Bahreini
  • 14,480
  • 11
  • 70
  • 137

1 Answers1

1

This error message happens when calling

 @Html.Partial("_AdSummary", null)

MVC seems to get confused by null view-models; it cannot tell what null's type is, so assumes the type is the same as the current view-model.

The solution is to make sure that Model.AdSummayResults is never null.