How to get a specific row from database in MVC 4

I have a model called PageModels

public class PageModels
{
    public int id { get; set; }

    public string title { get; set; }

    [DataType(DataType.MultilineText)]
    [AllowHtml]
    public string content { get; set; }

    public int parent { get; set; }

    [DataType(DataType.Date)]
    public DateTime created_at { get; set; }

    [DataType(DataType.Date)]
    public DateTime updated_at { get; set; }

    [DataType(DataType.Date)]
    public DateTime published_at { get; set; }
}

And based on this model I have a controller called PagesController. Here I have a method:

    public ActionResult showPage(string myTitle)
    {
        var query = from a in db.Pages
                    where a.title.Contains(myTitle)
                    select a;

        return View(db.Pages.FirstOrDefault());
    }

I want to be able to get the in the return value the content property of the page that has the title given in myTitle. I haven't been able to find a good way of doing that.

//EDIT

That error that I kept getting was my fault ... between trying to fix my problem and implementing your solution I changed the methods return type to PageModels and that's why it kept throwing me that error. Now it works but the view doesn't show anything. I'll try to fix that myself thanks for all the help.

Answers


You are getting the result of your filter to the variable query in the first line but you are returning something else (reading all Pages from DB and getting the first item from the collection) to the view.

You need to get the item from the variable query which has the result of your filter.

public ActionResult showPage(string myTitle)
{
    var query = from a in db.Pages
                where a.title.Contains(myTitle)
                select a;

    return View(query.FirstOrDefault());
}

Make sure to do a check for null after FirstOrDefault, otherwise you will run into an exception when there is no records in the collection.

public ActionResult showPage(string myTitle)
{
    var query = from a in db.Pages
                where a.title.Contains(myTitle)
                select a;
    var item=query.FirstOrDefault();
    if(item!=null)
       return View(item);
    else
       return View("NotFound");  //Let's show a view about item not found
}

Need Your Help

Is lazy loading supported in Hibernate Search?

hibernate lucene hibernate-search

Is lazy loading supported in Hibernate Search, that is, when I try to find some root indexed entities through Hibernate Search, then does Hibernate Search support lazy-loading annotations?

how to create and call lua function, that is in multiple files, from c++

c++ function lua

I need to create something like an onSomeEvent function, that'll be in every Lua plugin file. I have this: