Asp.net-mvc – MVC: The model item passed into the dictionary is of type X, but this dictionary requires a model item of type X

asp.net-mvcasp.net-mvc-3mvvmrazor

I am using EF model first and using viewmodels in MVC, I have problems with this error:

The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[NKI3.Models.Question]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[NKI3.ViewModels.IndexCreateViewModel]'.

This is my viewmodel:

public class IndexCreateViewModel
{
    public string QuestionText { get; set; }
    public string Sname { get; set; }
    public string Cname {get;set;}
}

This is my Action in my controller:

public ActionResult Index()
{
    var Q = db.Question.Include(a => a.SubjectType).Include(a => a.CoreValue);
    return View(Q.ToList());   
}

Here is my strongly typed view:

@model IEnumerable<NKI3.ViewModels.IndexCreateViewModel>

<h2>Index</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table>
    <tr>
        <th>
            QuestionText
        </th>
        <th>
            Sname
        </th>
        <th>
            Cname
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.QuestionText)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Sname)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Cname)
        </td>

    </tr>
}

</table>

I dont seem to find the solution for this, do I have to return my viewmodel inside the controller action index? Any help is appreciated.

Thanks in advance!

Best Regards!

Best Answer


See: note down below Would it help to return Enumerable?

 return View(Q.AsEnumerable()); 

EDIT: Yeah, I know my first shot was wrong!... did not noticed that your view wants a

@model IEnumerable<NKI3.ViewModels.IndexCreateViewModel>

I agree with the others about converting to the required return value to the matching type... or adjust the expecting type in the view... maybe you can take advantage of mapping framworks like automapper (http://automapper.org/) to help you to solve to mapping code between domain objects and viewmodels.

it's up to you - No need for further down voting...

Related Topic