我想使用ViewModel显示相关表格的详细信息视图。
所以我已经创建了详细信息操作方法,但它无法正常工作。
public ActionResult Details(int id)
{
IQueryable<EntryViewModel> query = (from cat in _db.Categories
join en in _db.Entries on cat.Id equals en.CategoryId
where en.Id == id
select new EntryViewModel
{
Title = en.Title,
Username = en.Username,
Password = en.Password,
Url = en.Url,
Description = en.Description,
Category = cat.Name
}).AsQueryable();
return View(query);
}
我收到此错误,无法找到解决方案。
The model item passed into the dictionary is of type
'System.Data.Entity.Infrastructure.DbQuery`1[App.ViewModels.EntryViewModel]',
but this dictionary requires a model item of type 'App.ViewModels.EntryViewModel'.
查看:
@model PasswordCloudApp.ViewModels.EntryViewModel
@{
ViewBag.Title = "Details";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Details</h2>
<fieldset>
<legend>EntryViewModel</legend>
<div class="display-label">
@Html.DisplayNameFor(model => model.Title)
</div>
<div class="display-field">
@Html.DisplayFor(model => model.Title)
</div>
<div class="display-label">
@Html.DisplayNameFor(model => model.Username)
</div>
<div class="display-field">
@Html.DisplayFor(model => model.Username)
</div>
<div class="display-label">
@Html.DisplayNameFor(model => model.Password)
</div>
<div class="display-field">
@Html.DisplayFor(model => model.Password)
</div>
<div class="display-label">
@Html.DisplayNameFor(model => model.Url)
</div>
<div class="display-field">
@Html.DisplayFor(model => model.Url)
</div>
<div class="display-label">
@Html.DisplayNameFor(model => model.Description)
</div>
<div class="display-field">
@Html.DisplayFor(model => model.Description)
</div>
</fieldset>
<p>
@Html.ActionLink("Edit", "Edit", new { /* id=Model.PrimaryKey */ }) |
@Html.ActionLink("Back to List", "Index")
</p>
有什么建议吗?
答案 0 :(得分:0)
您必须在视图中设置模型,如:
@model IQueryable<PasswordCloudApp.ViewModels.EntryViewModel>
答案 1 :(得分:0)
您的模型属于PasswordCloudApp.ViewModels.EntryViewModel
类型,但您正在从控制器传递IQueryable<EntryViewModel>
。
由于您希望给定一个id的单个项目,您可以更改您的控制器代码以返回该单个项目(如果找不到则可能返回404):
public ActionResult Details(int id)
{
EntryViewModel model = (from cat in _db.Categories
join en in _db.Entries on cat.Id equals en.CategoryId
where en.Id == id
select new EntryViewModel
{
Title = en.Title,
Username = en.Username,
Password = en.Password,
Url = en.Url,
Description = en.Description,
Category = cat.Name
}).FirstOrDefault();
if (model == null) return HttpNotFound();
return View(model);
}
答案 2 :(得分:0)
实际上你有PasswordCloudApp.ViewModels.EntryViewModel
绑定到你的视图但是你传递了Iqueryable,所以当你从动作返回视图时,你要关联结果的FirstOrDefault()或更改视图中的@model IQueryable<PasswordCloudApp.ViewModels.EntryViewModel>
。
public ActionResult Details(int id)
{
IQueryable<EntryViewModel> query = (from cat in _db.Categories
join en in _db.Entries on cat.Id equals en.CategoryId
where en.Id == id
select new EntryViewModel
{
Title = en.Title,
Username = en.Username,
Password = en.Password,
Url = en.Url,
Description = en.Description,
Category = cat.Name
}).AsQueryable();
return View(query.FirstOrDefault());
}