问题描述
我的音乐商店示例下面一起去尝试学习ASP.NET MVC。我创建一个应用程序的食谱。
I am following along with the music store example to try learn ASP.NET MVC. I'm creating a cookbook application.
我创建我的视图模型,看起来像这样:
I have created my viewmodel that looks like this:
namespace CookMe_MVC.ViewModels
{
public class CookMeIndexViewModel
{
public int NumberOfReceipes { get; set; }
public List<string> ReceipeName { get; set; }
}
}
我的控制器看起来像这样
my controller looks like this
public ActionResult Index()
{
var meals= new List<string> { "Dinner 1", "Dinner 2", "3rd not sure" };
//create the view model
var viewModel = new CookMeIndexViewModel
{
NumberOfReceipes = meals.Count(),
ReceipeName = meals
};
return View(viewModel);
}
最后我的看法是这样的。
Finally my view looks like this
@model IEnumerable<CookMe_MVC.ViewModels.CookMeIndexViewModel>
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th></th>
<th>
Meals
</th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
</td>
<td>
@item.ReceipeName
</td>
</tr>
}
</table>
我得到这个错误。
I get this error.
传递到字典中的模型产品类型的 CookMeIndexViewModel
,但本词典需要类型的模型项目的IEnumerable&LT; CookMeIndexViewModel&GT;
。
我也跟着例子。我看不到我在做什么错。我应该返回我的视图模型作为一个通用的列表?
I have followed the example. I can't see what I am doing wrong. Should I be returning my viewmodel as a generic list?
推荐答案
在你看来,你正在使用 @model IEnumerable的&LT; CookMe_MVC.ViewModels.CookMeIndexViewModel&GT;
这表明模型由视图预期是CookMeIndexViewModel的IEnumerable类型的。
In your view you are using @model IEnumerable<CookMe_MVC.ViewModels.CookMeIndexViewModel>
which indicates that the model expected by the View is of type IEnumerable of CookMeIndexViewModel.
然而,在控制器您传递类型CookMeIndexViewModel的对象作为模型返回视图(视图模型);
因此误差
However in the controller you are passing an object of type CookMeIndexViewModel as a model return View(viewModel);
hence the error.
要么改变视图有 @model CookMe_MVC.ViewModels.CookMeIndexViewModel
或传递的IEnumerable CookMeIndexViewModel作为模型,在控制器中的视图下方给出:
or pass a IEnumerable of CookMeIndexViewModel as model to the view in controller as given below:
public ActionResult Index()
{
var meals= new List<string> { "Dinner 1", "Dinner 2", "3rd not sure" };
//create the view model
var viewModel = new CookMeIndexViewModel
{
NumberOfReceipes = meals.Count(),
ReceipeName = meals
};
List<CookMeIndexViewModel> viewModelList = new List<CookMeIndexViewModel>();
viewModelList.Add(viewModel);
return View(viewModelList);
}
这篇关于该模型产品类型CookMeIndexViewModel,但需要IEnumerable类型℃的模型项目; CookMeIndexViewModel&GT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!