Div*_*Dan 32 asp.net asp.net-mvc-3 asp.net-mvc-viewmodel
我跟随音乐商店的例子来尝试学习ASP.NET MVC.我正在创建一本食谱应用程序.
我创建了我的viewmodel,如下所示:
namespace CookMe_MVC.ViewModels
{
public class CookMeIndexViewModel
{
public int NumberOfReceipes { get; set; }
public List<string> ReceipeName { get; set; }
}
}
Run Code Online (Sandbox Code Playgroud)
我的控制器看起来像这样
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);
}
Run Code Online (Sandbox Code Playgroud)
最后,我的观点看起来像这样
@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>
Run Code Online (Sandbox Code Playgroud)
我收到这个错误.
传递到字典中的模型项是类型
CookMeIndexViewModel,但此字典需要类型的模型项IEnumerable<CookMeIndexViewModel>.
我跟着这个例子.我看不出我做错了什么.我应该将我的viewmodel作为通用列表返回吗?
Cha*_*ndu 51
在您使用的视图中@model IEnumerable<CookMe_MVC.ViewModels.CookMeIndexViewModel>,表示View预期的模型类型为CookMeIndexViewModel的IEnumerable类型.
但是在控制器中,您将CookMeIndexViewModel类型的对象作为模型传递,return View(viewModel);因此会出错.
要么改变视图 @model CookMe_MVC.ViewModels.CookMeIndexViewModel
或者将IEnumerable的CookMeIndexViewModel作为模型传递给控制器中的视图,如下所示:
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);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
90620 次 |
| 最近记录: |