404 asp.net mvc - beginner question in routing - asp.net-mvc

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.

Related

MVC 4 routing to a controller

I am new to MVC and I am trying to mess around by creating a practice site which will be a gallery site for viewing and uploading images. The problem I encountered is that I cannot get the routing to work correctly.
Here is a link to my routing code and solution tree:
https://imgur.com/a/Oc1Tt?
Did I set the views and controller up incorrectly?
The error I get is: The view 'Index' or its master was not found or no view engine supports the searched locations. The following locations were searched:
Thanks for any input
Routing works by converting an incoming request to route values or by using route values to generate a URL. The route values are either set as parameters in the URL itself, as default values, or both (in which the defaults make the URL parameters optional).
You have not set any route values in your route. Since you don't have route parameters in the URL, you need to set defaults (controller and action are required by MVC).
routes.MapRoute(
name: "Gallery",
url: "Gallery/Index",
defaults: new { controller = "Gallery", action = "Index" }
);
That said, your Default route already covers this URL. You only need to add custom routes if you desire behavior that the Default route doesn't cover.
Also, if you change the view names so they don't match the name of the action method, you have to specify the name explicitly from the action method.
public ActionResult Index()
{
return View("~/Views/Gallery/GalleryView.cshtml");
}
By default MVC uses conventions. It is much simpler just to name the view Index.cshtml instead of GalleryView.cshtml so you can just return View from the action method.
public ActionResult Index()
{
return View();
}

MVC Route for a Single Controller to handle all Actions [duplicate]

I'm looking to do something similar to this post:
How to hide controller name in Url?
only without any sort of ID.
The server is running IIS 6 and the pages already show up without extensions so it's not a wildcard issue.
I'm looking to hit http://website.com/action-name
I have http://website.com/controller/action-name working
I'm assuming this is just a simple routing change that I am somehow goofing up. My current routing rule is:
routes.MapRoute(
"RouteName",
"{action}",
new { controller = "Home", action = "Index" }
);
Is your new routing rule positioned above the default routing rule of {controller, action, id} so that it has the opportunity to match first?
The problem is your default route is still probably in place so it is matching it first and defaulting the rest of the inputs it expects. Based on your comment that the controller/action is working makes me think you didn't remove it or it is appearing first. Can you post your entire RegisterRoutes?
Try making the route you defined the very first route and it should match almost anything you pass at it.
EDIT: Added what your RegisterRoutes should look like:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
// This will match anything so if you have something very specific with hard coded
// values or more items that will need to be match add them here above but do not
// add defaulted values so it can still fall through to this.
routes.MapRoute(
"RouteName",
"{action}",
new { controller = "Home", action = "Index" });
}

MVC route attribute exclude id

I have Home controller and Details action which received int id parameter.
I want map "/" url to Home controller, Details action, id = 1.
Also I want map urls like "/st15" to Home controller, Details action, id = 15.
So I wrote following attributes
[Route("~/{id:int:min(1):max(1)=1}")]
[Route("st{id:int:min(2)}")]
public ActionResult Details(int id)
{...}
The problem is url "/1" is also mapping to this action, but I need 404 for it
I would recommend leveraging the RouteConfig.cs file that is created with default MVC projects in VS2012.
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Details",
url: "/st{id}",
defaults: { controller = "Home", action = "Details", id = "1" }
);
routes.MapRoute(
name: "Default",
url: "/",
defaults: new { controller = "Home", action = "Details", id = "1" }
);
}
This will try to match urls to those two designated routes in the order you add them to your RouteConfig file. Since the 'Default' route doesn't have any additional parameters on its URL definition, a call to "/1" won't match a route and you'll get a 404.
If you used a blank project, adding a RouteConfig file is a trivial matter. Just add a RouteConfig.cs file and define the class to contain the RegisterRoutes method I listed, then in your Global.asax file's Application_Start function, add a line for
RouteConfig.RegisterRoutes(RouteTable.Routes);
And you'll be good to go.
(EDIT)
I'm not certain that there still won't be conflicts, but you can combine Attribute routing with the standard routing paradigm by simply adding
routes.MapMvcAttributeRoutes();
to your RegisterRoutes function, immediately after the IgnoreRoute call, and the application will always defer to your Route attributes first, then check the defined routes.
However, since you've indicated you'd like to avoid using the standard routing approach altogether, you could simply define the attributes to take the following routes:
[Route("~/")]
[Route("st{id:int:min(2)}")]
public ActionResult Details (int id = "1")
{...}
To set a default value for the id parameter and avoid trying to handle the case in the attribute itself. Since you define a minimum value for the {id} parameter in your second Route attribute, you shouldn't have to worry about the case of "/st" trying to route to that action. It wouldn't match either defined route and so would 404.

MVC Routing access path

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

Routing-MVC-ASP.NET

In most of the articles, they put this code and explain it but I feel I am not getting it. could any body expalain it in simple terms please.
This question is looks simple but I cannot get it correct in my head.
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
);
My Questions:
Why do we use route.IgnoreRoute and why the parameters in {} ?
Maproute has First parameter-Default, What that resembles, Second Parameter-"{controller}/{action}/{id}", What this for and third parameter, we use new ?
How do I intrepret these routing?
Why all these?
I have used webforms so far and Cannot get it in?
Any Gurus in MVC could explain all these please?
Why do we use route.IgnoreRoute
This tells routing to ignore any requests that match the provided pattern. In this case to ignore any requests to axd resources.
and why the parameters in {} ?
The {} indicates that the delimited string is a variable. In the ignore route this is used so that any .axd requests are matched.
Maproute has First parameter-Default, What that resembles,
The first parameter is the route name. This can be used when referring to routes by name. It can be null which is what I tend to use.
Second Parameter-"{controller}/{action}/{id}", What this for
This is the pattern that is matched. In this case it is setting up the default route which is a url formed by the controller name, action name and an optional id. The url http://mysite.com/Foo/Bar would call the Bar method on the Foo controller. Changing the url to http://mysite.com/Foo/Bar/1 would pass a parameter with the identifier id and value 1.
and third parameter,
The third parameter supplies defaults. In the case of the default route the default controller name is Home and the default action is Index. The outcome of this is that a request to http://mysite.com would call the Index method on the Home controller. The id part of the route is specified as being optional.
we use new ?
The new keyword is creating an object using the object initializer syntax that was introduced in version 3 of the .Net framework. Microsoft article.
The major advantage of using routing is that it creates a convention for your urls. If you created a new controller called Account and action methods called Index and Review then the methods would be availble at /Account and Account/Review respectively.
First of all: ASP.NET MVC is not a simple version of webforms.
MVC has a special structure. You can find a MVC description here: http://en.wikipedia.org/wiki/Model-View-Controller
MapRoute adds the URL structure mapping. For example, following the default route link like www.domain.com/home/users/1 means that the server should call the users action in the controller called home. The action gets a parameter called id with the value of 1.
If you want to add the new Route you can simply add this uin next way:
routes.MapRoute(
"NewRoad", // Route name
"/photos/{username}/{action}/{id}", // URL with parameters
new { controller = "Photos", action = "Index", string username, id = UrlParameter.Optional } // Parameter defaults
);
following this road the url will be: domain.com/photos/someuser/view/123. We can map the optional parameters like id, and static parameters, like username. By default we call photos controller and index action (if the action not set in ult, server will call default action "index", we set it in the route).

Resources