How to use MapRoute with Areas in MVC3 - c#

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.

Related

Issue with routing in MVC .net framework - some controllers not routing correctly

I've been working on a website, started off with the standard mvc template you get.
I have several controllers, Home, Admin, User along with the bundled ones you get like Manage and Account. From googling I've changed my routing so instead of mysite.com/home/index I can just go straight to mysite.com
This is what I currently have
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"OnlyAction",
"{action}",
new { controller = "Home", action = "Index" }
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
However, when using loginpartial template, the following action:
#Html.ActionLink("Hello " + User.Identity.GetUserName() + "!", "Index", "Manage", routeValues: null, htmlAttributes: new { title = "Manage" })
On my dev environment, instead of taking me to https://localhost:44363/Manage/Index it instead shows https://localhost:44363/Manage and a corresponding 404. I also get the same issue on the user controller.
What do I need to change in my routing? Its still one of the areas I'm struggling understanding
Many thanks

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 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!

How to create url route for specific Controller and Action in asp.net mvc3

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 = "" }
);

Parameter only route always being triggered MVC3

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!

The view 'Index' or its master could not be found

Today I've started restructuring my mvc project using areas. So I have some problems with it.
I make areas, move views and master pages, make routing, but when I'm trying to view any area page I get "The view 'Login' or its master could not be found."
Any suggestions? I've googled for some time, but didn't found any solution.
My global.asax routing:
routes.MapRoute("Areaname", "Areaname",
"Areaname/{controller}/{action}/{id}",
new { controller = "controllerName", action = "Home", id = UrlParameter.Optional },
new string[] { "path.to.area.controllers.Controllers" });
Area registration routing:
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"Areaname_default",
"Areaname/{controller}/{action}/{id}",
new { action = "Home", id = UrlParameter.Optional },
new string[] { "path.to.area.controllers.Controllers" }
);
}
It seems to be correct, but views are still unavailable.
Thanks in advance.
When using Areas, make sure you rewrite your action links like this:
Html.ActionLink("Invoicing link", "Index", "CustomerInvoices", new { area = "Invoicing" }, null)
In this example, you are linking to the "Index" action, inside "CustomerInvoices" controller, inside "Invoicing" Area.
Make sure you do the proper modifications to link to the Login action inside your Area!

Categories