I have two different controllers and I want both of them to use a Common View.
Is that possible?
Thanks in advance!!!!
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.
In Spring MVC, we can create multiple controllers at a time. It is required to map each controller class with @Controller annotation.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With