By default, MVC 4 in Visual Studio 2017 sets _Layout.cshtml as the default layout for all pages. I believe it's doing this 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 the home page)
I'm still not sure how Index is getting _Layout.cshtml. But what if I'm trying to set a different view - a login page - as the home page, like this?
Also I'm trying to get rid of the Reports, Accounts, Settings, and Logout <li>'s in the header so that the page matches the design above. I'll also need a container with a form inside of it.
I've tried creating a _Login view inside of /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 that's giving me an error:
How can I create a view and set that view as the default view for this MVC 4 Web App? Thanks
What you see in the defaults parameters as action is the name of the controller's method, not view, so you should create a method named Login in the Home controller and create the associated View for that (In the Login method right click and choose Add View). Then it will act as the default home page.
defaults: new { controller = "Home", action = "Login", id = UrlParameter.Optional }
So your Home controller looks like this:
public class HomeController : Controller
{
public IActionResult Login()
{
return View();
}
//other codes
}
Also if you do not want the default layout to be used in the Login page you may add this at top of the Login page
#{
Layout = "";
}
The error you see doesn't seem to be because of the layout page.
This error is because the Login Action is missing in the Home controller.
You see, The defaults specified are Controlller="Home", Action="Login".
i.e. The compiler looks for the Login action in the Home controller. and when it doesn't find, it throws this error!
you could get rid of it by adding the login action like:
public ActionResult Login(string Uname, string Password)
{
return View();
}
in the home controller! That's for the error in the question.
Here is the solution for your problem.
You could add a different layout for each of your views by adding a razor code like 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's path.
}
Hope this helps!
Related
I have the following in my RouteConfig.cs file
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
Home Controller has the following:
[Route("NewIncident")]
public ActionResult NewIncident()
{
var viewModel = new IncidentFormViewModel();
viewModel.NextPage = 2;
return View("NewIncident",viewModel);
}
[Route("EditIncident/{id?}")]
public ActionResult EditIncident(int? id)
{
return View("EditIncidentPage" + id);
}
[Route("SaveIncident")]
public ActionResult SaveIncident(IncidentFormViewModel incidentviewmodel)
{
return RedirectToAction("EditIncident/" + incidentviewmodel.NextPage);
}
From my index view, I can click a button that has the #Html.ActionLink as follows:
#Html.ActionLink("New Incident", "NewIncident", "Home", null, new { #class = "btn btn-primary" })
I access the site at http://sitename/ and it loads my index page. I can click the New Incident button and it loads http://sitename/NewIncident just fine, but when I click the Save button on the New Incident form, it calls the SaveIncident function just fine, but when it hits the return RedirectToAction("EditIncident/" + incidentviewmodel.NextPage); it sends me to http://sitename/Home/EditIncident/2 instead of just http://sitename/EditIncident/2.
Any idea why its adding the /Home in there?
The parts of the URL are http://sitename/Controller/Action/Parameter.
Your EditIncident ActionResult lives inside your Home Controller, and so you will therefore always see Homein front of EditIncident.
When you redirect to another Action, you can specify which controller to look for the ActionResult in with RedirectToAction("ActionName", "ControllerName"). If no Controller is specified, it assumes you want to use the same controller that you are currently in.
yes, Tot Zam are ok, and you need to create an action result method on your controller, this should be bind with a view
Found the issue.
Apparently I need to use Redirect(), not RedirectToAction() for my purposes.
Once I changed this, it rendered the correct URL without adding /Home to it
I'm trying to create custom urls for my LoadUser controller. I want the url to be
site.com/LoadUser/1.
The LoadUserByID route is above my default route. I keep getting the default error page
"Error. An error occurred while processing your request."
Can someone please point me in the right direction?
My code is as follows:
RouteConfig.cs
routes.MapRoute(
name: "LoadUserByID",
url: "LoadUser/{id}",
defaults: new { controller = "LoadUser", action = "ID", id = UrlParameter.Optional }
);
LoadUserController.cs
//
// GET: /LoadUser/[userid]
public ActionResult ID(int id)
{
ViewBag.Message = "ID page";
return View();
}
UPDATE
Code is fine and I'm new to MVC. I did not have a View created for LoadUser. I thought I could use the default view. Make sure to have a view created that correlates to your Controller/Action.
I am working in Asp.net mvc3 application.I have created url for product detail page like this
routes.MapRoute(
"ProductDetail",
"{category}/{title}-{id}",
new { controller = "ProductDetail", action = "Index" }
);
for other controller using this
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
Following code creating this url
www.example.com/Shoes/blackshoes-100
Now Problem is that i want to use this url for ProductDetail page if add any other controller and action name it will redirect to ProductDetail page like this
www.example.com/Home/Index-100
How can i restrict this url for ProductDetail Page?
is this right way to do this?
I wan to hide Controller and Action of Productdetail page.
Category,title and id values are changing for every product.
You have to define routes for any other page you have and map those routes before you map your peoduct detail route. Then the route maching mechanism will find them first and use them.
Of course you do not have to map route for every single action. You can create some prefixes for example for diffrent controllers like example below, to catch all routes for Home controller actions:
routes.MapRoute(
"Home",
"Home/{action}/{id}",
new { controller = "Home", action = "Index", id = "" }
);
I've got an Area in my web app called "Admin".
So, http://localhost.com/Admin goes to the Home Controller and Index Action in the Admin Area.
However, I want to be able to hit the Admin Home Controller and Index Action with the following Url:
http://localhost.com/Hello
I've got this as my attempt:
routes.MapRoute(
"HelloPage",
"Hello/{controller}/{action}",
new{area= "Admin", controller = "Home", action = "Index"},
new[] { typeof(Areas.Admin.Controllers.HomeController).Namespace });
As you can see I'm specifying the namespace and the area, but all I get is the routing error:
The view 'Index' or its master was not found or no view engine supports the searched locations.
It's not searching in the Admin area.
Any ideas?
Try this:
routes.MapRoute(
"HelloPage",
"Hello/{controller}/{action}/{id}",
new { area = "Admin", controller = "Home", action = "Index", id = UrlParameter.Optional }
);
And then add this to your Admin controller action:
if (!this.ControllerContext.RouteData.DataTokens.ContainsKey("area"))
{
this.ControllerContext.RouteData.DataTokens.Add("area", "Admin")
}
You can check here for further documentation.
The problem was that I was setting the route in Global.asax.
I should have been setting it in the AreaRegistration in the Admin area. Once I did that the problem was fixed.
I have two very simple routes
routes.MapRoute(
"post", // Route name
postPage + "/{slug}", // URL with parameters
new { controller = "Home", action = "Article" } // Parameter defaults
);
routes.MapRoute(
"page", // Route name
"{slug}", // URL with parameters
new { controller = "Home", action = "Page", slug = homePage} // Parameter defaults
);
And here is my controller logic
public ActionResult Article(string slug)
{
return View(repo.GetPost(slug));
}
public ActionResult Page(string slug)
{
if (slug.ToLower() == MetaData.PostsPage.ToLower())
return View("listPosts", repo.GetAllPosts());
else
return View("page", repo.GetPage(slug));
}
homePage and postPage are set from value's in the database. Allowing the user to define the default page as well as the page to show posts.
My issue occurs when adding an area named "Admin". I get a controller added to my RouteTable
context.MapRoute(
"Admin_default",
"Admin/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional }
);
Now when a user Access Admin/Account/Logon the page loads fine, but my debugger still tries to go into the Home controller and the Page action. But the RouteDebugger says it doesn't match the current request. I'm puzzled on how to fix this.
RouteDebugger screenshot: http://i.stack.imgur.com/7cpHm.png
Debugger going into my HomeControler Page AtionResult: http://i.stack.imgur.com/uSJBK.png
Actually the problem is, Area routes are overriding the global routes, to distinguish both the routes set the relevant namespace of area's controller in the context.MapRoute method in adminAreaRegistraton.cs file. i.e.
context.MapRoute(
"admin_default",
"admin/{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
null,
new string[] { "MVCApplication1.Areas.admin.Controllers" }
);
I found out the issue.
I had a favicon.ico set in the main area of my site, but not the Admin area.
So when I went to the Admin area the browser made a request for favicon.ico that got picked up by that route. Thats why my routes looked fine in the RouteDebugger, because they were.
Thanks for the help Kundan!