Understanding ASP.NET MVC Routes reg - c#

I've created a system in MVC using the NerdDinner tutorial as a base to work off.
Everything was working fine until I used single action methods such as
Here is the global.asax.cs
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "mysample", id=UrlParameter.Optional }
);
which routes to
http:localhost/Home/mysample
i just want to create routes which has more than one action in the sense
http:localhost/<controller>/<action>/<params>
ex: localhost/mycontroller/myaction/details/myname
Any help much appreciated.
Thanks.
update 1:
i have writen router like this as
routes.MapRoute(
"myname", // Route name
"{controller}/{action}/{details}/{myname}", // URL with parameters
new { controller = "mycontroller", action = "myaction", details= "details", myname= "" } // Parameter defaults
);
and retried the value with following syntax as
String name=RouteData.Values["myname"].ToString();
it works fine .
but even though the url called as
localhost/mycontroller/myaction/details
its being routed to that controller and error is being thrown as null reference...
how to avoid it?

You can't define multiple actions in one MVC route.
In MVC routing configuration is used for mapping your Controlers and Actions to user friendly routes and:
Keep URLs clean
Keep URLs discoverable by end-users
Avoid Database IDs in URL
Understanding default route config:
routes.MapRoute(
name: "Default", // Route name
routeTemplate: "{controller}/{action}/{id}", // URL with parameters
defaults: new { controller = "Home", action = "mysample", id=UrlParameter.Optional }
);
The "routeTemplate" property on the Route class defines the Url
matching rule that should be used to evaluate if a route rule applies
to a particular incoming request.
The "defaults" property on the Route class defines a dictionary of
default values to use in the event that the incoming URL doesn't
include one of the parameter values specified.
Default route will map all requests, because it has defined default values for every property in routeTemplate, {} means that property is variable, if you not provide value for that param in URL, it will try to take default value if you provide it. In default route it has defined defaults for controller, action and id param is optional. That means if you have route like this:
.../Account/Login
It will take you to Account controller, Login action and because you didn't specified prop and it is defined as optional it will work.
.../Home
This will also work, and it will take you to Home contoller and mysample action
When you define custom route, like you did:
routes.MapRoute(
"myname", // Route name
"{controller}/{action}/{details}/{myname}", // URL with parameters
new { controller = "mycontroller", action = "myaction", details= "details", myname= "" } // Parameter defaults
);
You didn't specified myname as optional and you didn't specified it your route, that means that your URL: localhost/mycontroller/myaction/details wan't be handled by your custom route myname. It will be handled by default route. And when you try to access your myname param in controller it wan't be there and you will get null reference error. If you want to specifie default value of your parameter if not present in url you need to do that in your controller. For example:
public class MyController : Controller
{
public ActionResult MyAction(string details = "details", string myname = "")
{
...
and change your custom route to:
routes.MapRoute(
"myname", // Route name
"{controller}/{action}/{details}/{myname}", // URL with parameters
new { controller = "mycontroller", action = "myaction", details= UrlParameter.Optional, myname= UrlParameter.Optional } // Parameter defaults
);
But you can define only one controller and only one action, rest of the routeTemplate are parameters.
You can't define two action in one route. It make no sense.

Related

Force questionmark to show in querystring where only ID param is passed

I've implemented code to encrypt my query string parameter names and values. The code i have implemented will only encrypt query string that contain ?. (This is to prevent encryption of unneeded URL's, such as the .css files).
A way to combat this would be to always show the ? in query strings when only the ID parameter is passed.
For example I would like: http://domain/controller/Action/17
To show as: http://domain/controller/Action/?id=17
I understand that I probably need to edit my routes, I've tried adding the ? symbol to the route which throws the error : The route URL cannot start with a '/' or '~' character and it cannot contain a '?' character.
My routes are defined as:
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute("favicon.ico");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Login", id = UrlParameter.Optional } // Parameter defaults
);
How can I get my query strings to show like the example given above?
Don't define your parameters in routes.
ASP.NET automaticaly will add the question mark.
You can then call http://domain/controller/Action?id=17 and it will route to
public ActionResult Action(int id) { }
Update: If you want to kill domain/controller/action/id format completely, you need to define the route as:
routes.MapRoute(
name: "Parameterless", //or any name
url: "YourController",
defaults: new { controller = "YourController", action = "YourAction" }
);
Now you can use domain/controller/action?id={id} and domain/controller/action/id will 404.
If you are getting a Server Application Error, you need to provide more details, since it might be related to something else.

ActionLink shows wrong url

I have some pre-defined URLs in routing table actually directing to same controller and action, but different language. For example
routes.MapRoute(
"Contact", // Route name
"contact", // URL with parameters
new { controller = "Home", action = "Contact", lang="en" } // Parameter defaults
);
routes.MapRoute(
"Contact2", // Route name
"iletisim", // URL with parameters
new { controller = "Home", action = "Contact", lang="tr" } // Parameter defaults
);
When i use Html.ActionLink in View and run application, URL shows the first route, for example:
#Html.ActionLink(Resources.Contact, "Contact", "Home")
When current language is tr when page rendered URL is : /contact which should be /iletisim instead.
When i change the order of route mappings then en language pages shows wrong URL.
How can I solve this problem?
When matching a route from ActionLink, you must take all of the parameters that the route generates into consideration. The framework will always return the first match for the supplied route values.
In your case, you are supplying the route values:
controller = "Home"
action = "Contact"
Which given the lack of other information will match your Contact route (the first route with controller = "Home", action = "Contact").
If you want to match a specific route, then you need to pass the lang route value as well.
#Html.ActionLink(Resources.Contact, "Contact", "Home", new { lang = "tr" }, null)
That will match the Contact2 route.
Alternatively, you can put the lang into the URL of the page, which would ensure that it is part of the current request as shown in ASP.NET MVC 5 culture in route and url
. Then MVC will automatically supply this value to all of your ActionLinks and other UrlHelper based methods.

Different url from controllername in asp.net MVC

I have a controller called CarController located in a folder called Buy. So the url becomes www.website.com/Buy/Car
How do I make the url be instead "/purchase/vehicle" without changing controller and folder name?
Thanks!
You need to define a new route for it
routes.MapRoute(
name: "VehicleRoute",
url: "purchase/vehicle",
defaults: new { controller = "Car", action = "TheAction" }
);
Just make sure you have placed it before the default route.
You can do this with a custom route. See here for informations about routing. You can then create your custom route with default values for the Controller and the action, something like:
routes.MapRoute(
"MyRoute",
"purchase/vehicle",
defaults: new { controller = "Car", action = "Buy" }
);
You have to put in there the correct controller name and the action you want to call.

MVC 3 How to use MapRoute

Could someone show me how to use the MapRoute method? I have tried creating my own routes, but it's not working. What i want to accomplish is a route that routes "http://servername/home/default.aspx" into controller "Home" and action "Default". Also, would it be possible to say that if the user is browsing the default.aspx "file", it would actually point to the "Index" action?
I have tried reading the MSDN references and googling, but it didn't make me any wiser.
Probably too late to help the developer who raised the question but may help someone else. New to MVC but what I found is the map routes seem to be processed in the order they are added. I had a similar problem, my specific route was not working until I started adding the default route as the last route.
If the default map route is added before your custom one and your custom URL matches the structure defined by the default map route you will never reach your custom route.
The route you want to configure the first part of your question is:
routes.MapRoute(
"",
"home/default.aspx",
new { controller = "Home", action = "Default" }
);
Assuming you wish to 'browse' default.aspx with some sort of parameter you can do something like:
routes.MapRoute(
"",
"home/default.aspx/{param}",
new { controller = "Home", action = "Default", param = UrlParameter.Optional }
);
And you would then need to create your Default action to accept string param.
You also have to make sure the parameter name is the same as the action's parameter name.
Example:
routes.MapRoute(
name: "MyName",
url: "{controller}/{action}/{myParam}",
defaults: new { controller = "MyController", action = "MyAction", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
MyController:
public ActionResult MyAction(string myParam = "")
{
}

Can't bind to parameter

I've got the default routing:
routes.MapRoute(
"Shortie", // Route name
"{controller}/{id}", // URL with parameters
new { controller = "Ettan", action = "Index", id = "id" } // Parameter defaults
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Ettan", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
I've got a controller: NewsController. It has one method, like this:
public ActionResult Index(int id)
{
...
}
If I browse to /News/Index/123, it works. /News/123 works. However, /News/Index?id=123 does not (it can't find any method named "index" where id is allowed to be null). So I seem to be lacking some understanding on how the routing and modelbinder works together.
The reason for asking is that I want to have a dropdown with different news sources, with parameter "id". So I can select one news source (for instance "sport", id = 123) and it should be routed to my index method. But I can't seem to get that to work.
The ASP.NET MVC Routing works using reflection. It will look inside the controller for a method matching the pattern you are defining in your routes. If it can't find one...well you've seen what happens.
So the answer is (as posted in the comments) to change the type of your id parameter to a Nullable<int> i.e. int?.

Categories