In ASP.NET MVC, I have a BooksController
which provides functionality for viewing books. I want www.mydomain.com/books
to return a list of all my books (and it's associated "All books" html page), while www.domain.com/books/c-sharp-for-dummies
to fetch all information for the "C# for dummies" book (again, with it's "Single book" html page).
It's trivial to create an Index
method with a bookName
parameter.
public class BooksController
{
public ActionResult Index(string bookName)
{
if (string.IsNullOrEmpty(bookName)
{
//return all books here
}
else
{
//return single book here
}
}
}
Index
has it's associated Index.cshtml
view page, but then I'd have to do a Razor check in the view to ascertain whether to load the "all books" HTML/CSS, or "single book" HTML/CSS - it's like the view contains two pages in one, which I find counter-intuitive.
What is a good (or even conventional) approach to such scenarios? Do I just create two cshtml
files, one for "all books" and one for "single book", and just return the appropriate view depending on whether a bookName
parameter was provided or not?
public class BooksController
{
public ActionResult Index(string bookName)
{
if (string.IsNullOrEmpty(bookName)
{
//return all books viewmodel and related view
}
else
{
//return single book viewmodel and related view
}
}
}