Wednesday, May 8, 2013

MVC - Share views for multiple controllers

Moving on to MVC projects and I must start of by saying that it seems like we are back to writing a lot of code on the "view" the way we used to write way back in the ASP days :-) Anyway, the topic I was planning to discuss today was not that.

I had this requirement where the view I had created was just perfect 2 of my controllers. I thought this was a straight forward requirement and went about creating the view in one of the "views/WList/Common.cshtml" folder and then called it from an action within "Controllers/WListController".

 public ActionResult MyAction()
{
return View("Common", WListModel);
}

It worked fine till I tried to created another controller called "Controllers/AnotherController" and tried to return the "Wlist" view in the action result (same code as above). While writing the code, I was not sure how this code in this controller would be able to find the view, but decided to give it a try. It failed as expected because it searched for the view in the "views\Another" folder and could not find it there.

This used to be so easy with a redirect statement :-).

Looking closer at the error raised, I noticed, it actually lists all the folders it searched for the view and realized that it also looks in the "shared" folder. I knew that the shared folder was used for partial views. So would the solution be to create a partial view from "Wlist" view and then render the partial view from 2 other views within "views/Wlist" and "views/Another" folder? But before I try that, I thought maybe I could also just try moving the Common.cshtml to "Shared" folder and try it.  I tried and it worked.

So to conclude, the "view/shared" folder can hold partial and also complete views that you might want to share between multiple controllers.