Routing-MVC-ASP.NET - asp.net-mvc

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).

Related

MVC .NET 4 MapRoute + ActionLink or RouteLink issue

Okay, so here's the deal. I've got controller called "Hotel" with view called "Index", where I'm trying to produce code allowing me to generate links in form of:
../Hotel?id=1
with ID passed as argument. To do so, I've tried using MapRoute:
#Html.RouteCollection.MapRoute("Hotel", "../{controller}/{id}", new { controller = "hotel" });
together with ActionLink:
#Html.ActionLink("More >>>", "", "Hotel", new { id = item.HotelId }, null)
But the outcome link goes like this:
Hotel/Index/1
Which leads to correct location, but burns visual consistency of all links at my website. I've tried RouteLink as well, but with no success.
Thanks in advance!
Do you want to make all links in the application use the standard querystring format for parameters named "id"? If so, removing the {id} from url and defaults object in the "Default" route should do that for you just fine.
If you want to limit it to the "Hotel" controller, you are on the right track w/ the custom route. First, make sure the custom route comes before the default route definition, and second, define it with nothing beyond the controller/action like:
routes.MapRoute(
"HotelRoute", // Route name
"Hotel/{action}/", // URL with parameters
new { controller="Hotel", action = "Index" } // Parameter defaults
);
Any params you pass in should then be appended to the query string as a name/value pair.

How can I achieve clean URL routing with custom user ID?

My ASP.NET MVC site allows users to register and give themselves user names, which will be unique and allow others to browse their pages with a clean URL that includes their name, like Twitter, Facebook, LinkedIn etc. do.
For example:
mysite.com/michael.guthrie
mysite.com/john
mysite.com/john/images
mysite.com/john/blog
etc.
The problem is that the first URL segment might be used for other "regular" controllers/actions, like:
mysite.com/about
mysite.com/register
So basically I seek for a routing scheme that says something like: If the first URL segment is a known controller, treat it as a controller (and parse the relevant action and parameters as usual), but if not - treat it as a user name, and pass it to a dedicated controller+action which will parse it and continue accordingly.
I don't want a solution that will enforce me to add routes for every specific controller that I have, such that after the routing module will go over all of them and won't find a match, it will get to the last one which defines a route for this special user name segment. The reason is primarily maintenance (I must remember to add a route every time I code a new controller, for example.)
I assume I can implement my own MvcRouteHandler / IRouteHandler but I feel there must be simpler solution that won't have me tweak MVC's out-of-the-box routing mechanism.
Note: I've read How to achieve nice litle USER page url like facebook or twitter? and it doesn't answer my question, it's just says that there is a URL rewriting module.
Do you know any good, elegant, clean way to achieve that?
You should have your first route be your Usesr route, with a route constraint along the lines of what I described in this answer: MVC routing question.
If your route is in the form {username}/{controller}/{id}, this route should cover all contingencies.
in the global.asax file you can map your routes
in the registerRoutes() method you can do something like this:
routes.MapRoute(
"ToonStudenten", // Route name
"{controller}/{action}/{userID}, // URL with parameters
new { controller = "Docent", action = "ToonStudenten", userID = UrlParameter.Optional} // Parameter defaults
);
I believe you can change the way your views look with this mapRouting, not entirely sure how though.. will try and search it up
You may want to take a look at this post:
MVC 3 keeping short url
You don't need to set a route for each URL. With a little help from route constraints you can do something like this:
routes.MapRoute(
"Home", // Route name
"{action}", // URL with parameters
new { controller = "Home", action = "Index" }, // Parameter defaults
new { action = "TaskA|TaskB|TaskC|etc" } //Route constraints
);
routes.MapRoute(
"Account", // Route name
"{action}", // URL with parameters
new { controller = "Account", action = "Logon" }, // Parameter defaults
new { action = "Logon|Logoff|Profile|FAQs|etc" } //Route constraints
);

MVC Routing: Trying to get dynamic root value working

I am trying to define dynamic sections of my site with the root url of the site. I am having some trouble defining the right MVC Route for it. Can someone please help.
My desired url will look like this: http://website.com/[dynamic-string]
But I have other standard pages like: http://website.com/about or http://website.com/faq or even just http://website.com.
My routes don't work correctly with that dynamic string. As shown below.
This is the route for the dynamic-string.
routes.MapRoute(
"CommunityName", // Route name
"{communityName}", // URL with parameters
new { controller = "Community", action = "Community", communityName = UrlParameter.Optional }
);
This is the route for all other STANDARD PAGES
routes.MapRoute(
"Default", // Route name
"{action}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
My routes just don't match up. Everything either gets diverted to one or the other route depending on which route is declared first.
There is no difference between the two routes you mention. How can MVC know which url should be mapped to communityName and which to action? Any url can match both.
You can define your standard pages as a route (before the CommunityName route) or you can catch them in your Community action, see if the name matches a function in your Home controller and then call the right action function.
I've never done this before but you might be able to create a more intelligent routehandler that looks at your controller actions, checks if the action really exists and if true selects that route.
this is beacuse the routes are effectively the same. When you declare the action route you do not state any constraints to the route, for this reason anything will be assumed to be a the action name.
If you want two routes to capture at the same level then you must constrain the action names to those that exist on your controller, this way if it does not match it will pass to the next route.
You can see an example of and advanced constraint here:
http://blogs.planetcloud.co.uk/mygreatdiscovery/post/Custom-route-constraint-to-validate-against-a-list.aspx

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.

ASP.NET MVC routing issues

I'm having some issues trying to setup my Routing in MVC. I think I understand how it works, but I just can't seem to set the proper paths.
Basically I want to do something similar to how StackOverflow works so:
http://localhost/faq
I want this to grab the HomeController, hit the faq action and return the faq view. I can't seem to figure out how to do this.
Also, I tried adding a new route for something like this:
http://localhost/Boxes/25
So, Boxes is the controller, 25 is obviously the id(parameter). Similar to how stackoverflow has: https://stackoverflow.com/questions/[question number]/[question title]
So I tried doing this:
routes.MapRoute(
"Boxes",
"Boxes/{boxnumber}",
new {
action="Details", cubenumber = ""
}
);
with no success.
I've also downloading the Route Tester app, but that doesn't seem to be helping at this point. Most likely I need to really read up on how routing works, but was just wondering if someone could point me in the right direction right now instead of me having to spin my wheels.
Thanks a lot guys!
Try the following:
routes.MapRoute(
null, // optional route name
"faq",
new { controller="Home", action="Faq" } );
routes.MapRoute(
null, // optional route name
"Boxes/{boxnumber}",
new { controller="Boxes", action="Details", boxnumber = ""} );
// Original route, if needed, should come AFTER more specialized routes.
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } ); // Parameter defaults
Some notes that may help you understand this better:
the controller and action parameters must be specified, either explicitly in the incoming URL or via defaults that you specify (if missing in incoming URL)
the order of adding routes is significant because the first match will be used for each incoming URL. In the above example, if the original route is added first, the other ones will never be matched (because the original route specifies defaults for all parameterized parts of the URL)
route name is optional, only needed if you are using route names to generate outbound URLs
When you define a route, it has to at minimum contain two pieces of information: a controller and an action. Those values can either come through as a parameter (i.e. a "{parameter}" portion in the URL pattern), or as a default value.
The route example that you pasted above includes an action but it doesn't contain a controller, so it isn't capable of satisfying a request. Since your controller name is "BoxesController", you could simply add "controller='Boxes'" to the default values of that route and you'd be good.
To achieve the faq route, you could simply define a route whose URL was "faq" and had the default values: controller="Home", action="Faq".

Resources