DPS
DPS

Reputation: 87

How to fetch one row from db in asp mvc

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>

Upvotes: 0

Views: 5216

Answers (3)

Dismissile
Dismissile

Reputation: 33071

If you are using Entity Framework:

var singleItem = db.pages.Find(id);

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):

var singleItem = db.pages.Find(key1, key2);

Upvotes: 0

cbrooker
cbrooker

Reputation: 1

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;

 public ActionResult Index()
        {
            string page = db.pages.where(p => p.PageName == "index").FirstOrDefault().PageName;

            return View(page);
        }

There in your page, Model will now be that single string value and you can do this;

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">   
     <%= Model %>
</asp:Content>

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.

public class MypageViewModel
{
    public string PageName { get; set; }   
}

Then do this in the controller

public ActionResult Index()
        {
            MypageViewModel MyModel = new MypageViewModel();
            MyModel.PageName = db.pages.where(p => p.PageName == "index").FirstOrDefault().PageName;

            return View(MypageViewModel);
        }

Hope that helps.

Upvotes: 0

goenning
goenning

Reputation: 6654

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.

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    <%= Html.Encode(item.Model.Text) %>
</asp:Content>

Upvotes: 1

Related Questions