MVC Routing access path - asp.net-mvc

I am quite new to MVC. I am facing a problem with routing right now. My project URL is /account/Create. I can access controller and do my stuff for Create, but
I need to access /account controller because I need to write code in that level.
/account/create - I can access the code this level
/account - dont know how to access this controller
Project Stucture:
Sample Project
Controler
Model
View
What am I supposed to change in the following code?
//global.asax.cs
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } //Parameter defaults
);
}

/account/create is accessing code in the Account controller. Create has to be a method on the Account controller (unless you modify the default routes). Any public method you define on the account controller is accessible via /account/method URL. Based on the route you posted, going to /account URL is going to call the account controller Index method:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
**new { controller = "Home", action = "Index", id = UrlParameter.Optional }** // Parameter defaults
);
That action = "Index" part above is defining what the default method on the account controller is, so going to /account URL is equivalent in this case to /account/index URL
And I just noticed that you spelled account wrong in the question, not sure if that may be your issue ;)
Update
Not sure if this is what you're after, but if you need to write code at the /Account level you can do this in the constructor of the controller.

Unless you substantially customize MVC, then controllers correspond to classes derived from Controller in mvc, and actions correspond to methods on those controllers.
What are you trying to achieve when you say you can't access the controller /Account?
The controller is only a container for Actions so you need to specify an Action. Of course, you can have a default Action in case an action isn't specified. That is specified in default the route above. It's called Index

Related

.NET MVC custom route different default controller

.NET MVC. I am having some problems defining and using custom routes.
I have a controller with just 2 actions. These action methods receive 2 parameters each. I have added a custom route in RouteConfig.cs (before the default route), like this
routes.MapRoute(
name: "customRoute",
url: "MyController/{action}/{entityType}/{id}",
defaults: new { controller = "MyController", action = "Index", entityType = UrlParameter.Optional, id = UrlParameter.Optional }
);
this works if MyController does contain an Index method (and corresponding view).
the problem is, MyController does not contain an Index method (only the 2 action methods refered before), and I want the route.default to be something like Home/Index instead. but if I change the route to this:
routes.MapRoute(
name: "customRoute",
url: "MyController/{action}/{entityType}/{id}",
defaults: new { controller = "Home", action = "Index", entityType = UrlParameter.Optional, id = UrlParameter.Optional }
);
it does not work. Apparently, the controller in route.url must be the same as the one in route.defaults...
CORRECTION: the route works for a correct url, but for an incorrect one (for example adding another parameter at the end) it shows 404 error (makes sense, because MyController.Index does not exists)
so, how can this be achieved?
url: "MyController/{action}/{entityType}/{id}"
Here, what you are saying is the URL pattern for your custom route should start with MyController(My/).
If the url pattern does not match with the configured routes(including the default one) you will have 404 Error.
I can suggest 2 ways of achieving what you want...
Either create a third method in your MyController that will act as the default one and its task would be to redirect to Home/Index.
Or
Create a new method in Home controller having parameters for entityType and Id.
You can't create an overload for Home/Index because you can only have a maximum of 2 action methods with the same name on a controller.
See this.
Routing: The current request for action [...] is ambiguous between the following action methods

ASP.NET MVC4 Routing - Multiple routes to the same location

I am in the process of setting up a Single Page Application (SPA) and would like to setup, currently two routes. For instance:
Route 1: http://localhost - this is the default route which requires authentication (Admin area)
Route 2: http://localhost/<client>/<clients project name>/ - this does not require authentication (view only)
In the admin area, they setup the <client> and <clients project name>, therefore I know I need to setup this configuration in MVC4 Routes, but it is unclear to me how I would approach this.
Another caveat would be, if the <clients project name> was not entered into the URL, it would present a search page for that client.
One of the great things about routing in MVC is the ability to route anything to anywhere, regardless of whether the url matches the naming of controllers and action methods. The RouteConfig allows us to register specific routes to cater for this. Let me show you how you can achieve this.
Route 1:
This is handled by the default route in the route config.
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home",
action = "Index",
id = UrlParameter.Optional });
Hitting http://localhost will take you to the Home controller and the Index action method.
Route 2:
We can set up one route that will cater for http://localhost/<client> and http://localhost/<client>/<clients project name>
routes.MapRoute(
"Client",
"{client}/{title}",
new { controller = "Home",
action = "Client",
title = UrlParameter.Optional });
Hitting either http://localhost/bacon or http://localhost/bacon/smokey will take you to the Home controller and the Client action method. Notice the title is an optional parameter this is how we can get both urls to work with the same route.
For this to work on the controller end our action method Client would need to look like this.
public ActionResult Client(string client, string title = null)
{
if(title != null)
{
// Do something here.
}
}

ASP.MVC 3 routing : how to get url with default action included?

Suppose I have the following routing
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } );
Now, when you generate an url using Url.Action("Index","MyController") you will get as expected : /MyController
But in one exceptional case, I would like to get the full url /MyController/Index
(without changing the routing)... does anyone know if this is possible?
It is possible. But you need to modify the routing.
Create an own routing class that derives Route
Override the GetVirtualPath() method to include /index for the pages that needs it.
Configure the default route using your routing class instead.
I am afraid this is not possible. And it shouldn't matter as both urls will resolve to the same controller action.

How does MVC routing understands the URL?

Global.asax.cs has the following code on initialization:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
What I'm asking is, how does it know that what it gets for "{controller}" will be the name of the Controller class to be invoked? Are there tokens defined somewhere? if so, can I list them?
If I define additional tokens (like "{lang}") will it assume they are additional parameters?
(I'm developing a custom URL rewrite/redirect handler, and I need it to work with MVC...)
What is the most practical way to define custom patterns and "aliases" for URLs?
The Mvc runtime has the controller and action tokens hardcoded. In addition there is also "area" but thats about it.
#TDaver If I define additional tokens (like "{lang}") will it assume they are additional parameters?
yes. If you define, for instance, a parameter like lang, it wil detect it. Think about like that, it will be the querystring field called lang of the page. and you can create a route for a pretyy url. Like below;
routes.MapRoute(
"Default", // Route name
"{lang}/{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
so the url will be like ; http://example.com/en/home/about
Also, the most important part of routing is to understand that the routes will be picked by order. for instance, if you have multiple routes matching your current request, the first route will be picked by MVC Framework.
I reccomend you to have a look at phil haccked's RouteDebugger
Also you can create route constraints for advanced routing options as well.

404 asp.net mvc - beginner question in routing

This is a beginner level question for asp.net MVC
I have the following code in global.asax.cs
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = (string)null } // Parameter defaults
);
}
in Homecontroller.cs i have updated the Index method as follows
public ActionResult Index(string id)
{
ViewData["Message"] = "Welcome to ASP.NET MVC1!"+ id;
return View();
}
My understanding is, if I give the url http://localhost/mvc1/default/1 it should work
instead it is throwing up 404 error
any help what is the reason behind this
I'm assuming your application is called "mvc1" and that's the root of your project. If that's the case:
So "default" is the name if your route, not the name of the action. Basically what the routing engine does is look for a controller and action that matches requests coming in. Given the route you have setup, it would break down like this:
http://localhost/MVCApplication1/default/1
(cont) (action)
If certain parts of the route are omitted, it will attempt to fill in the missing values with the defaults you have specified. As you can see, there is no controller named DefaultController in your project, and thus it uses the default you've specified which is Home. It then tries to find an action method called default and fails again, so it uses the default value in your route, which is Index. Finally, you have 2 segments left in your URL, and no route matches that pattern (2 segments after the action), so it can't find the right place to go.
What you need to do is remove one of your segments, and this should work. Routing can be a little tricky, so I would recommend reading up on it.
The URL you're requesting is asking for a controller called "mvc1" and an action called "default" which will receive an id of "1". Since you don't have a controller named "mvc1" (I assume?), you're getting the 404 error.
The defaults for controller and action are only used if controller and action aren't provided. Since you provided controller and action, MVC is looking for them specifically.

Resources