Asp.net mvc 4 如何在mvc4视图中显示从控制器返回的db上下文数据

Asp.net mvc 4 如何在mvc4视图中显示从控制器返回的db上下文数据,asp.net-mvc-4,Asp.net Mvc 4,如何在mvc4视图中显示db上下文数据?以下是我的控制器代码: public ActionResult Detail(int id) { AuthorContext oauthorContext = new AuthorContext(); Author oauthor = oauthorContext.Authors.Single(x => x.authorid == id); return View(oauthor);

如何在mvc4视图中显示db上下文数据?以下是我的控制器代码:

   public ActionResult Detail(int id)
    {

        AuthorContext oauthorContext = new AuthorContext();
        Author oauthor = oauthorContext.Authors.Single(x => x.authorid == id);
        return View(oauthor);
    }
鉴于:

@{
ViewBag.Title = "Author Detail";
}

<h2>AuthorDetail</h2>

@{
    foreach Context in 
}
@{
ViewBag.Title=“作者详细信息”;
}
作者详情
@{
中的foreach上下文
}

在视图中显示db上下文数据的标准方法是将数据放入模型或视图模型中,然后将该模型传递给视图

当您将
Author
传递到视图中时,您已经有了一个良好的开端

如果您的视图是强类型的
作者
,您应该可以使用
模型
对象访问视图中的
OAutor

在你看来

<h2>@Model.SomeAuthorProperty</h2> 
@Model.SomeAuthorProperty

例如,在
h2
元素中显示
oauthor.SomeAuthorProperty

在我看来,您缺少的是视图顶部的@model Author:

@model Author

@{
ViewBag.Title = "Author Detail";
AuthorName = Model.Name //assuming Name is a property of Author
}

<h2>@AuthorName Detail</h2>
@模型作者
@{
ViewBag.Title=“作者详细信息”;
AuthorName=Model.Name//假设Name是Author的属性
}
@AuthorName详细信息

我没有获取对象oauthorcontext@{foreach Context in}