Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can two different controllers access a single view in mvc?

I have two different controllers and I want both of them to use a Common View.

Is that possible?

Thanks in advance!!!!

like image 768
RL89 Avatar asked Sep 01 '12 13:09

RL89


People also ask

Can a view be shared across multiple controllers in MVC?

Yes, It is possible to share a view across multiple controllers by putting a view into the shared folder. By doing like this, you can automatically make the view available across multiple controllers.

Can you have more than one controller in MVC?

In Spring MVC, we can create multiple controllers at a time. It is required to map each controller class with @Controller annotation.

How can we call a view from another controller in MVC?

By default, ASP.NET MVC checks first in \Views\[Controller_Dir]\ , but after that, if it doesn't find the view, it checks in \Views\Shared . The shared directory is there specifically to share Views across multiple controllers. Just add your View to the Shared subdirectory and you're good to go.

Can we use 2 models in a view?

You can use multiple models in a single view by creating a common model for all the models that are to be used in a single view. To achieve this, refer to the following steps. First, create a new model (common for all models) and refer all other models that are to be used in the same view.


1 Answers

Yes.Mention the view full path in the View method.

public class UserController : Controller
{
   public ActionResult ShowUser()
   {
     return View();
   }
}
public class AccountController : Controller
{
   public ActionResult ShowAccount()
   {
     return View("~/Views/User/ShowUser.cshtml");
   }
}

If the name of your Views are same in both the controllers, You can keep the Common view under the Views/Shared directory and simply call the View method without any parameter. The View name should be same as the Action method name.

public class UserController : Controller
{
   public ActionResult ShowUser()
   {
     return View();
   }
}
public class AccountController : Controller
{
   public ActionResult ShowUser()
   {
     return View();
   }
}

Assuming you have a View called ShowUser.cshtml under Views/Shared folder.

like image 155
Shyju Avatar answered Oct 21 '22 02:10

Shyju