如何在asp mvc中从数据库中获取一行
ASP.net mvc 对我来说是新的,有一段时间我使用 php (没有 mvc),但现在我感兴趣,如何从数据库中获取一行?没有 foreach,例如在标题中...
这里是一些代码: 控制器
public ActionResult Index()
{
var pages = (from page in db.Pages where page.PageName == "index" select page).ToList();
return View(pages);
}
视图:
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
<% foreach (var item in Model)
{ %>
<%= Html.Encode(item.Text) %>
<% }
%>
</asp:Content>
ASP.net mvc in new for me, for some time I used php (no mvc), but now i'm interested, how I can fetch one row from db? without foreach, for example in title...
here is some code:
controller
public ActionResult Index()
{
var pages = (from page in db.Pages where page.PageName == "index" select page).ToList();
return View(pages);
}
view:
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
<% foreach (var item in Model)
{ %>
<%= Html.Encode(item.Text) %>
<% }
%>
</asp:Content>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您正在做的是创建一个列表数据类型变量并将其作为模型传递到您的视图。假设这是您的页面需要的唯一数据。这就是你要做的;
在您的页面中,模型现在将是单个字符串值,您可以执行此操作;
尽管最佳实践是为页面创建一个 ViewModel,其中仅包含页面所需的属性,并将其作为模型传递。
然后在控制器中执行此操作
希望有帮助。
What you're doing there is creating a List datatype variable and passing it in as the Model to your view. Assuming this is the only piece of data your page needs. Here's what you would do;
There in your page, Model will now be that single string value and you can do this;
Although it is best practice to create a ViewModel for the page with the just the properties your page will need and pass that in as the Model.
Then do this in the controller
Hope that helps.
如果您使用实体框架:
这将使用实体的主键。
如果您有一个由多个属性组成的复合主键,“查找”仍然有效(因为它可以采用多个值):
If you are using Entity Framework:
This will use the Primary Key of your entity.
If you have a composite primary key consisting of multiple properties, Find will still work (because it can take multiple values):
在您的控制器中,您可以使用
.FirstOrDefault()
方法代替.ToList()
方法,这将仅返回数据库中的第一行。那么在你看来你就不需要 foreach 了。
In your controller, instead of
.ToList()
you can use the.FirstOrDefault()
method, this will return only the first row from the database.Then in your view you won't need the foreach.