Routes in ASP.NET MVC - c#

I am trying to route a link in MVC project.
I tried two methods:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
//method1
// routes.MapPageRoute("SchoolPage", "School", "~/home", false);
//method2
routes.MapRoute(name: "SchoolPage",url: "School", defaults: new { controller = "Home", action = "Index" });
}
For both methods I get the error:
HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.

You need to specify the custom route first. Default route has no constraints so it will match to any URL. When you make a request ot http://example.org/School, ASP.NET MVC will look for a controller named SchoolController using the default route. You have to make sure it matches to SchoolPage route first by placing it before the default route.
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(name: "SchoolPage",url: "School", defaults: new { controller = "Home", action = "Index" });
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}

Related

Why don't only typing controller name in the browser redirects to the action that I have defined in the route config?

I have this controller Login which has a get method named Login.
Now If I type a controller name in browser link then it should automatically pick Login method among other methods or If I type action name without controller then it should pick.
I have done this in RouteConfig:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute
(
name: "Login",
url: "Login",
defaults: new {controller= "Login", action= "Login", id= UrlParameter.Optional }
);
}
But it doesn't work. But if I place it above the default route then it works but the problem is that upon loading the project it directly goes to login page.

ASP.NET MVC 5 Url Rewriting to encompass all actions in controller?

I would like to know if it's possible to write a rule in the Route.Config file that can encompass all actions within a single controller? I have read this article but it's a little bit above me (I have just started with url rewriting and routing and the terminology is not familiar).
I have managed to change one of my actions from mydomain.co.za/Trainee/Action?id=123 to mydomain.co.za/Trainee/Action/123 but I was hoping to be able to encompass all actions in the Trainee controller, such that you can have one rule to produce Trainee/Action1/123 or Trainee/Action2/123 This is the code I used:
routes.MapRoute(
name: "ActionRewrite",
url: "Trainee/Action/{id}",
defaults: new { controller = "Trainee", action = "Action" }
);
On a side note, is it possible to hide the parameters in a URL as well, such that you can simply have mydomain.co.za/Action/ no matter what the user is doing?
Try this:
routes.MapRoute(
name: "ActionRewrite",
url: "Trainee/{action}/{id}",
defaults: new { controller = "Trainee", action = {action} }
);
Bear in mind that you can use wildcards your url match.
If you wanted you can specify that the {id} paramater remain optional which means it will also match actions that do not specify parameters.
Try this one ..
Url Rewiring in using custom id and name .
Add in app startup Route config .
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
routes.MapRoute(
name: "contactus",
url: "contactus",
defaults: new { Controller = "Cms", action = "Index", id = (int)Common.CMSContactUs },
namespaces: new[] { "QZero.Controllers" }
);
routes.MapRoute(
name: "aboutus",
url: "aboutus",
defaults: new { Controller = "Cms", action = "Index", id = (int)Common.CMSAboutUs },
namespaces: new[] { "QZero.Controllers" }
);
routes.MapRoute(
name: "useragreement",
url: "useragreement",
defaults: new { Controller = "Cms", action = "Index", id = (int)Common.CMSUserAgreement },
namespaces: new[] { "QZero.Controllers" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
namespaces: new[] { "QZero.Controllers" }
);
}
}

How to create query string using Html.ActionLink

In my mvc3 razor project my I have action link
#Html.ActionLink("ActionLinkName","Count","Home",new{id = 3})
This generates localhost/Home/Count/3
but I want it to create localhost/Home/Count?id=3
What changes in route should I make ?
This is because the default route that's used with new MVC projects includes an {id} segment. Removing that segment from your default route will make your existing code produce a query string.
Change this:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
To this:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}", // URL with parameters
new { controller = "Home", action = "Index" } // Parameter defaults
);
Since the default (fallback) route that Asp.Net registers is including an {id} parameter in the url pattern:
// Default
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
Your generated url adheres to this fallback pattern ({controller}/{action}/{id}) and appends your id using /{id}.
You'll need to register a custom route before the default route to exclude the {id}:
routes.MapRoute(
name: "Count",
url: "Home/Count",
defaults: new { controller = "Home", action = "Count" }
);
You can also try to remove the {id} from the default pattern (if it won't affect other actions) or change your id parameter in the Count action to a different name.
remove {id} from default config
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new {
controller = "Home",
action = "Index",
id = UrlParameter.Optional }
);
}
TO
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}",
defaults: new {
controller = "Home",
action = "Index" }
);
}

MVC4 Route as /{controler}-{id} instead of /{controler}/{id}

During my work I must solve one URL rewriting problem. I have to use URLs as a template:
{controller}/{action}-{id}
instead of
{controller}/{action}/{id}
so the processed url should look like:
myController/myAction-128
where 128 is a parameter
My route map:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "NewRoute", // Route name
url: "{controller}/{action}-{id}/{extId}", // URL with parameters
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional, extId = UrlParameter.Optional } // Parameter defaults
);
}
Controller code:
[HttpGet]
public ActionResult DocumentDetails(int? id)
{
if (doc.HasValue)
{
...
}
}
This route doesn't provide any successful results. I still have 404 Errors. When I use / instead of "-" everything is ok, but my JS View environment won't work.
Is there something I could do to fix this? All help will be appreciated, thanks.
Routes are evaluated in the same order as you defined them, so make sure you respect the same order. Also adding a constraint for the id (as being a number for example) would help the routing engine disambiguate your routes. Not to mention that in your example you have made the id token optional which of course is not possible, only the last part of a route can be optional.
So:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "NewRoute",
url: "{controller}/{action}-{id}/{extId}",
defaults: new { controller = "Home", action = "Index", extId = UrlParameter.Optional },
new { id = #"\d+" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
I'm thinking your request is being processes by the first routing rule and then action-id is considered as a whole action and not being found.
Set your NewRoute before the Default route. Just move the code up.

Default to Area Controller

For an ASP.NET MVC application, I have 2 controllers with the name Home. One of the controllers is in an Areas section, one is not. If someone goes to the base path /, I am trying to default to the controller in the Areas section. I am under the impression that this is possible. I have the following setup which I believe is supposed to make that happen -
When I go to /, I am still taken to the Controller in MVCArea01/Controllers/ and not MVCArea01/Areas/Admin/Controllers/.
(in case the code in the image is too small to see, here is the code for the method, RegisterRoutes)
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
new[] {"MVCAreas01.Areas.Admin.Controllers"} // I believe this code should cause "/" to go to the Areas section by default
);
}
What is the correct solution?
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,
area = "Admin"
}
}
#ABogus
I modified the AdminAreaRegistration.cs file. Refer the image below
Also I modified the Route.config as below.
I got the output as like this
You can download the sample project from https://www.dropbox.com/s/o8in2389e8aebak/SOMVC.zip
You should create additional route for your starting page, that will direct processing to the right controller:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Home_Default",
"",
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
new[] { "MVCAreas01.Areas.Admin.Controllers" });
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
namespaces: new[] { "MVCAreas01.Controllers" }
);
}

Categories