How to change default view in MVC 4 web application
By default, MVC 4 in Visual Studio 2017 sets _Layout.cshtml
as the default layout for all pages. I believe this is done in App_Start/RouteConfig.cs
:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
(Index is set as home page)
I'm still not sure how Index gets _Layout.cshtml
. But what if I try to set a different view - the login page - like the home page, for example?
Also I am trying to get rid of reports, accounts, settings and output <li>'s
in the header to make the page fit the project above. I also need a container with a form inside it.
I tried to create a view _Login
inside /Home
and /Shared
and changed "Index"
to "Login"
in App_Start/RouteConfig.cs
:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Login", id = UrlParameter.Optional }
But this gives me an error:
How do I create a view and set that view as the default view for this MVC 4 web application? Thanks to
source to share
What you see in the default options as action
is the controller method name, not a view, so you have to create a named method Login
in the controller Home
and create an appropriate view for it (In Login
right click and select Add View). Then it will act as the default home page.
defaults: new { controller = "Home", action = "Login", id = UrlParameter.Optional }
So your controller Home
looks like this:
public class HomeController : Controller
{
public IActionResult Login()
{
return View();
}
//other codes
}
Also, if you don't want the default layout to be used on the login page, you can add this at the top of the login page
@{
Layout = "";
}
source to share
The error you are seeing does not seem to be due to the layout page.
This error occurs due to missing Home Controller login action.
You see, these default values: Controlller="Home", Action="Login"
.
those. the compiler looks for the "Login" action on the Home controller. and when it doesn't find it, it throws this error!
you can get rid of it by adding a login action like:
public ActionResult Login(string Uname, string Password)
{
return View();
}
in your home controller! This is for the error in the question.
Here is the solution to the problem. You can add a different layout for each of your views by adding razor code as shown below to specify the layout for the view.
@{
Layout = "~/Views/Shared/_Layout.cshtml";
//This is the path to the layout. You could change this to your custom layout path.
}
Hope this helps!
source to share