加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – MVC:传入字典的模型项是X类型,但是这个字典需要

发布时间:2020-12-16 09:23:58 所属栏目:asp.Net 来源:网络整理
导读:我首先使用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.Collectio
我首先使用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]'.

这是我的viewmodel:

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

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

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

这是我的强类型视图:

@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>

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

提前致谢!

最好的祝福!

解决方法

请参阅:下面的注释
返回Enumerable会有帮助吗?

return View(Q.AsEnumerable());

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

@model IEnumerable<NKI3.ViewModels.IndexCreateViewModel>

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

这取决于你 – 无需进一步投票……

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读