Home/MVC/Retrieve Views from Different Folders in MVC

Retrieve Views from Different Folders in MVC

In this post we will discuss how to use the view which is placed inside another folder in our application and
how to use that view in our controller. In simple, if we place the view inside the folder views -> Users -> Admin -> index.cshtml instead of views -> Users -> index.cshtml.

When to use?

In the below image, all the views has been placed under Views -> Users. Here we can see there is no structured hierarchy of the views. So we are creating a separate folder for Admin, Non-Admin, Super Admin to create a view based on their role.

RetriveViewFromDifferentFolder1-dotnet-helpers

Creating View in different folder :

EG :  views -> Users -> Admin -> index.cshtml)

For the default view location the action will be like below

public ActionResult Admin()
{
return View();
}
public ActionResult NonAdmin()
{
return View();
}
public ActionResult SuperAdmin()
{
return View();
}

For the customized view location, the action will be look below. We can’t redirect particular view from here.

public ActionResult Admin()
{
return View(“Admin/AdminHomePage”);
}
public ActionResult NonAdmin()
{
return View(“NonAdmin/NonAdminHomePage”);
}
public ActionResult SuperAdmin()
{
return View(“SuperAdmin/SuperAdminHomePage”);
}

Creating Controller based on the Customized View Location :

Here it can’t redirect to the particular view location by right click -> Go To View option. It will show “Unable to find a matching view.”

RetriveViewFromDifferentFolder3-dotnet-helpers

 

Keep Cool Coding !!!

Leave a Reply