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

RegEx javascript text file

javascript regex

I have an textfile with this structure:

my “click” addEventListener does not work well

javascript ajax

I'm using the following code to add listeners to a (that I append to a TBODY in the table) so i can see the nice highligh effect when I put my mouse over the TR.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.