Add a simple route - asp.net-mvc

I'm trying to add a route that shows some data based on a string parameter like this:
http://whatever.com/View/078x756
How do I create that simple route and where to put it?

In your global.asax.cs file, you add the following lines:
routes.mapRoute(
// The name of the new route
"NewRoute",
// The url pattern
"View/{id}",
// Defaulte route data
new { controller = "Home", action = "Index", id = "078x756" });
Make sure you add them before the registration of the default route - the ASP.NET MVC Framework will look throught the routes in order and take the first one that matches your url. Phil Haack's Routing Debugger is a valuable tool when troubleshooting this.

Routes are usually configured in the Application_Start method in Global.asax. For your particular case you could add a route before the Default one:
routes.MapRoute(
"Views",
"View/{id}",
new
{
controller = "somecontroller",
action = "someaction",
id = ""
}
);
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new
{
controller = "home",
action = "index",
id = ""
}
);

Routes are added in the global.asax.cs
Example of adding a route:
namespace MvcApplication1
{
// Note: For instructions on enabling IIS6 or IIS7 classic mode,
// visit http://go.microsoft.com/?LinkId=9394801
public class MvcApplication : System.Web.HttpApplication
{
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 = "" } // Parameter defaults
);
routes.MapRoute(
"WhatEver"
"{View}/{id}",
new {controller = "Home","action = "Index", id="abcdef"}
);
}
protected void Application_Start()
{
RegisterRoutes(RouteTable.Routes);
}
}
}
}

Related

Custom Routing in mvc4

I am using mvc4 framework and .net framwork 4.5. I need a url like this:
www.examples.com/name (note: 'name' will be change dynamically)
which routes to the same page.
I have tried like this but getting error
My action method is like this:
public ActionResult Userlist(string status)
{
return View();
}
Route Config
routes.MapRoute(
"user",
"{status}",
new { controller = "Home", action = "Userlist" }
);
How can I create a route syntax and redirect this to a controller?
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
// Add this route config
routes.MapRoute(
name: "Default_Userlist",
url: "{status}",
defaults: new { controller = "Home", action = "Userlist" },
namespaces: new[] { "MyMvcProject.Controllers" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
namespaces: new[] { "MyMvcProject.Controllers" }
);
}
Don't forget to replace the "MyMvcProject" with the name of your project.
Issue
This is a bad practice because the value of the status could easily cause conflicts with your action methods.

can not map a route for a specific controller in mvc 4

I have a controller named Registration and an action method in it as the following:
public JsonResult GetReqs(GridSettings gridSettings, int rt)
{
...//whatever
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
So I added a route and now my RouteConfig.cs is like this:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "RegReq",
url: "{Registration}/{GetReqs}/{rt}",
defaults: new { controller = "Registration", action = "GetReqs", rt = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
However I can't access the rt parameter and the action method GetReqs isn't called(I set a breakpoint on it but nothing happened). Where is the mistake?
Edit: Link example I tried : ~/Registration/GetReqs/1
I think you need to remove the brackets in your first route:
routes.MapRoute(
name: "RegReq",
url: "Registration/GetReqs/{rt}",
defaults: new { controller = "Registration", action = "GetReqs",
rt = UrlParameter.Optional }
);
The default route has {controller} to tell MVC to use the string in that section of the url as the controller name. You know the controller, so you just need to match the specific string.

Parameter value not passed in ASP.NET MVC route

I'm learning about creating custom routes in ASP.NET MVC and have hit a brick wall. In my Global.asax.cs file, I've added the following:
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 Custom Route.
routes.MapRoute(
"User_Filter",
"home/filter/{name}",
new { controller = "Home", action = "Filter", name = String.Empty }
);
}
The idea is for me to able to navigate to http://localhost:123/home/filter/mynameparam. Here is my controller:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult Filter(string name)
{
return this.Content(String.Format("You found me {0}", name));
}
}
When I navigate to http://localhost:123/home/filter/mynameparam the contoller method Filter is called, but the parameter name is always null.
Could someone give a pointer as to the correct way for me to build my custom route, so that it passes the name part in the url into the name parameter for Filter().
The Default route should be the last one.
Try it this way:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
// My Custom Route.
routes.MapRoute(
"User_Filter",
"home/filter/{name}",
new { controller = "Home", action = "Filter", name = String.Empty }
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
I believe your routes need to be the other way round?
The routes are processed in order, so if the first (default, OOTB) route matches the URL, that's the one that'll be used.

ASP.NET MVC Routing - "Blank" Route

Can I set up a route that will get mapped from a root-level URL like this?
http://localhost:49658/
I'm using the VS2010 built-in web server.
Attempting to set up a route with a blank or a single-slash URL string doesn't work:
routes.MapRoute(
"Default",
"/",
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
It results in the error "The route URL cannot start with a '/' or '~' character and it cannot contain a '?' character.". Thanks in advance! My entire route definition is here:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"EditingTitles", // Route name
"{controller}/{action}/{startingLetter}", // URL with parameters
new { controller = "Admin", action = "Index", startingLetter = UrlParameter.Optional } // Parameter defaults
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
What are you trying to achieve here... a URL that looks like this? http://www.acme.com/ ? Because if you are, the default route will achieve that when none of the parameters are specified.
// Default Route:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = String.Empty } // Parameter defaults
);
Using ASPNET MVC5:
RouteConfig.cs file:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Homepage",
url: "",
defaults: new { controller = "Content", action = "Index" }
);
routes.MapRoute(
name: "foo",
url: "bar",
defaults: new { controller = "Content", action = "Index" }
);
routes.MapMvcAttributeRoutes();
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{title}",
defaults: new { controller = "Content", action = "Details", title = UrlParameter.Optional }
);
}
Plus:
If you wishes to redirect your homepage to another route automatically, like "http://www.yoursite.com/" to "http://www.yoursite.com/bar", just use the method RedirectToRoute():
public class ContentController : Controller
{
public ActionResult Index()
{
return RedirectToRoute("foo");
}
}

Ambiguous Controller Names in ASP.NET MVC

I tried implementing Phil's Areas Demo in my project
http://haacked.com/archive/2008/11/04/areas-in-aspnetmvc.aspx.
I appended the Areas/Blog structure in my existing MVC project and I get the following error in my project.
The controller name Home is ambiguous between the following types:
WebMVC.Controllers.HomeController
WebMVC.Areas.Blogs.Controllers.HomeController
this is how my Global.asax looks.
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapAreas("{controller}/{action}/{id}",
"WebMVC.Areas.Blogs",
new[] { "Blogs", "Forums" });
routes.MapRootArea("{controller}/{action}/{id}",
"WebMVC",
new { controller = "Home", action = "Index", id = "" });
//routes.MapRoute(
// "Default", // Route name
// "{controller}/{action}/{id}",// URL with parameters
// new { controller = "Home", action = "Index", id = "" }
// // Parameter defaults
//);
}
protected void Application_Start()
{
String assemblyName = Assembly.GetExecutingAssembly().CodeBase;
String path = new Uri(assemblyName).LocalPath;
Directory.SetCurrentDirectory(Path.GetDirectoryName(path));
ViewEngines.Engines.Clear();
ViewEngines.Engines.Add(new AreaViewEngine());
RegisterRoutes(RouteTable.Routes);
// RouteDebug.RouteDebugger.RewriteRoutesForTesting(RouteTable.Routes);
}
If I remove the /Areas/Blogs from routes.MapAreas, it looks at the Index of the root.
In ASP.NET MVC 2.0, you can include the namespace(s) for your parent project controllers when registering routes in the parent area.
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = "" },
new string[] { "MyProjectName.Controllers" }
);
This restricts the route to searching for controllers only in the namespace you specified.
Instead of WebMVC.Areas.Blogs and WebMVC, use WebMVC.Areas.Blogs and WebMVC.Areas.OtherAreaName. Think of the area name as the namespace root, not an absolute namespace.
You can prioritize between multiple controllers with the same name in routing as follows
E.g., I have one controller named HomeController in Areas/Admin/HomeController
and another in root /controller/HomeController
so I prioritize my root one as follows:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", // Parameter defaults
id = UrlParameter.Optional },
new [] { "MyAppName.Controllers" } // Prioritized namespace which tells the current asp.net mvc pipeline to route for root controller not in areas.
);

Resources