globetrotter
globetrotter

Reputation: 1047

Combining two views in one vs returning two views for same controller action

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 
         }
     }
}

Upvotes: 0

Views: 1295

Answers (1)

Shyju
Shyju

Reputation: 218732

You should create 2 separate action methods in your controller. One for returning the view with all the books and one to return the details of a single book.

You can define routing definition in such a way, so that the request comes for yourSite/books, it will be handled by the index action and yourSite/books/somebookname, it will be handled by the Details action method. Here is how you will do it with attribute routing.

public class BooksController : Controller
{
    [Route("books")]
    public ActionResult Index()
    {
        // to do : Get all the books and pass it to the view.
        return View();
    }
    [Route("books/{bookName}")]
    public ActionResult Details(string bookName)
    {
       // to do : Get single book using the bookName parameter
       // and pass that to the view.
       return View();
    }
}

Now in your index.cshtml view, you can display all the books and in the Details.cshtml view, you can display the details of a specific book.

Upvotes: 3

Related Questions