MVC:传递到字典的模型产品的X型,但本词典需要X类型的模型项目 [英] MVC: The model item passed into the dictionary is of type X, but this dictionary requires a model item of type X

查看:80
本文介绍了MVC:传递到字典的模型产品的X型,但本词典需要X类型的模型项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我第一次使用EF模型和MVC使用的ViewModels,我有这个错误的问题:

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]'.

这是我的视图模型:

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>

我不似乎找到解决的办法,我必须回到控制器动作索引中的我视图模型?任何帮助是AP preciated。

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.

在此先感谢!

祝商祺!

推荐答案

请参阅:下面记下
它是否有助于返回可枚举?


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

 return View(Q.AsEnumerable()); 


编辑:是的,我知道我的第一个镜头是错误的...没有注意到,您的看法想要一个


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

@model IEnumerable<NKI3.ViewModels.IndexCreateViewModel>

我同意有关转换为所需的返回值的类型匹配的其他...
或调整视图中的期望类型...
也许你可以利用测绘framworks像automapper(http://automapper.org/)来帮助您解决域对象和的ViewModels之间的映射code。

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

这篇关于MVC:传递到字典的模型产品的X型,但本词典需要X类型的模型项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆