MVC:传递到字典中的模型项是X类型,但是这个字典需要X类型的模型项

Obs*_*vus 3 asp.net-mvc mvvm razor asp.net-mvc-3

我首先使用EF模型并在MVC中使用viewmodels,我遇到此错误的问题:

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]'.
Run Code Online (Sandbox Code Playgroud)

这是我的viewmodel:

public class IndexCreateViewModel
{
    public string QuestionText { get; set; }
    public string Sname { get; set; }
    public string Cname {get;set;}
}
Run Code Online (Sandbox Code Playgroud)

这是我在我的控制器中的动作:

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

这是我的强类型视图:

@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>
Run Code Online (Sandbox Code Playgroud)

我似乎没有找到解决方案,我是否必须在控制器动作索引中返回我的viewmodel?任何帮助表示赞赏.

提前致谢!

最好的祝福!

sil*_*ter 7


请参阅:下面的注释是否有助于返回Enumerable?

 return View(Q.AsEnumerable()); 
Run Code Online (Sandbox Code Playgroud)

编辑:是的,我知道我的第一枪是错的!...没有注意到你的观点想要一个

@model IEnumerable<NKI3.ViewModels.IndexCreateViewModel>
Run Code Online (Sandbox Code Playgroud)

我同意其他人关于将所需的返回值转换为匹配类型...或者在视图中调整期望类型...也许你可以利用像automapper这样的映射框架(http://automapper.org/)帮助您解决在域对象和视图模型之间映射代码的问题.

这取决于你 - 无需进一步投票......