So I'm trying to make a simple MVC system that will search through a database of books by author and/or title. I have a model called Book.cs with title and author properties. In my controller I made an ActionResult as follows:
public ActionResult Search(string theAuthor, string theTitle)
{
if (theAuthor == null && theTitle == null)
{
ViewBag.title = "Search for a book by author and/or title";
}
else
{
ViewBag.title = "Results:";
}
List<Book> allBooks = db.Books.ToList();
List<Book> booksFound = new List<Book>();
foreach (Book theBook in allBooks)
{
if (theAuthor != null && theTitle != null)
{
if (theBook.author == theAuthor && theBook.title == theTitle) booksFound.Add(theBook);
}else if (theAuthor == null)
{
if (theBook.title == theTitle) booksFound.Add(theBook);
}else if (theBook == null)
{
if (theBook.author == theAuthor) booksFound.Add(theBook);
}
}
return View("Search", booksFound);
}
Now, this returns a List of books, so I assume that in my view I have to use List<Book>
model, and so I did (@model List<Book>
). But the problem is how am I going to send data to the action result? I tried using
@Html.TextBoxFor (x => x.author)
But that gives the
'
List<Book>
' does not contain a definition for 'author' and no extension method 'author' accepting a first argument of type 'List<Book>
' could be found (are you missing a using directive or an assembly reference?)
error. Now that makes sense to me because I guess I can't access model class property if my model is a list. So am I doing something wrong or I should use another way to pass data? Thanks