Asp.net 如何在视图MVC4的详细操作中显示相关表中的数据?
我想使用ViewModel显示相关表中的详细信息视图 所以我创建了详细操作方法,但它不起作用Asp.net 如何在视图MVC4的详细操作中显示相关表中的数据?,asp.net,asp.net-mvc,entity-framework,asp.net-mvc-4,Asp.net,Asp.net Mvc,Entity Framework,Asp.net Mvc 4,我想使用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
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);
}
视图:
有什么建议吗?您必须在视图中设置模型,如:
@model IQueryable<PasswordCloudApp.ViewModels.EntryViewModel>
您的模型的类型为PasswordCloudApp.ViewModels.EntryViewModel,但您正在从控制器传递IQueryable
由于您希望单个项目具有一个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);
}
实际上,您已将PasswordCloudApp.ViewModels.EntryViewModel与视图绑定,但您正在传递Iqueryable,因此在从操作返回视图时,您可以将结果的FirstOrDefault关联起来,或者更改视图中的@model Iqueryable
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());
}
请发布您的查看内容!我在找的地方。谢谢但现在我又犯了一个错误。”System.Linq.IQueryable'不包含'Title'的定义,并且找不到接受'System.Linq.IQueryable'类型的第一个参数的扩展方法'Title'。是否缺少using指令或程序集引用?。有什么问题吗?使用如下元素:@Html.TextBoxFormodel=>model.FirstOrDefault.Title
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);
}
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());
}