问题
这显然不起作用,因为它是在黑暗中拍摄的,什么是检索具有特定ID的数据然后发送/显示数据以查看的最佳方式
模型
public partial class Profile
{
public int Id { get; set; }
public string Firstname { get; set; }
public string Lastname { get; set; }
}
控制器
public ActionResult Details()
{
ProfileContext db = new ProfileContext();
var data = (from c in db.Profiles
where c.Id == 1
select c).ToString();
return View(data);
}
查看
@model Learning4.Profile
@{
ViewBag.Title = "Details";
}
<h2>Details</h2>
<div>
<h4>Profile</h4>
<hr />
<dl class="dl-horizontal">
<dt>
@Html.DisplayNameFor(model => model.Firstname)
</dt>
<dd>
@Html.DisplayFor(model => model.Firstname)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Lastname)
</dt>
<dd>
@Html.DisplayFor(model => model.Lastname)
</dd>
</dl>
</div>
数据
| ID | 名字 | 姓氏 |
| 1 | John | Doe |
答案 0 :(得分:1)
您想要返回单个对象,因此需要使用.FirstOrDefault()
(您的查询返回一个集合,即使它只包含一个元素)
public ActionResult Details()
{
ProfileContext db = new ProfileContext();
var data = (from c in db.Profiles
where c.Id == 1
select c).FirstOrDefault();
// or
data = db.Profiles.FirstOrDefault(x => x.Id == 1);
return View(data);
}