Optional parameters in MVC3 routing - asp.net-mvc-3

I am trying to create routes which can apply 1 and 2 type of URLs.
1 - First route will be at the start of application and I want 2 type of URLs that can used to access index page. I cannot hit below route when I have URL with Home at the end instead going to type 2.
http://www.example.com Or http://www.example.com/Home
routes.MapRoute(
"Default",
"{controller}/{action}",
new { controller = "Home", action = "Index", name = "" }
);
2 - This type of URL is passing "Name" parameter to load contents from DB. I want this URL like
http://www.example.com/Page?name=Contact Or
http://www.example.com/Page?name=Contact&id=22
But I want above URL like
http://www.example.com/Contact Or http://www.example.com/About
Or
http://www.example.com/Contact/22 Or http://www.example.com/About/33
Where
Contact and About are values for "Name" parameter passed in URL. Below is the Route used
routes.MapRoute(
"DynamicPages",
"{name}",
new { controller = "Home", action = "Page" }
);

Here is a possible solution. I am not sure if this is the right way to do this.
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
//To match http://www.mysite.com
routes.MapRoute(
"RootUrl",
"",
new { controller = "Home", action = "Index",
id = UrlParameter.Optional }
);
//To match http://www.mysite.com/Home
routes.MapRoute(
"RootUrlWithAction",
"Home/{action}",
new { controller = "Home", action = "Index" }
);
//To match http://www.mysite.com/Contact Or
// http://www.mysite.com/About Or
// http://www.mysite.com/Contact/22 Or
// http://www.mysite.com/About/33
routes.MapRoute(
"DynamicPages",
"{name}/{id}",
new { controller = "Home", action = "Page",
id = UrlParameter.Optional }
);
// Everything else
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index",
id = UrlParameter.Optional } // Parameter defaults
);
}
Tested the following routes. Here the site root url is http://localhost:5879/. Refer the output screenshots provided below for each of the below mentioned scenario.
http://localhost:5879/ --> Uses first route map
http://localhost:5879/Home --> Uses second route map
http://localhost:5879/Contact --> Uses third route map
http://localhost:5879/About/33 --> Uses third route map
http://localhost:5879/Home/Page?name=Contact&id=22 --> Uses third route map
http://localhost:5879/Home/Index/2 --> Uses fourth route map
Screenshot #1:
Screenshot #2:
Screenshot #3:
Screenshot #4:
Screenshot #5:
Screenshot #6:
Hope that gives you some idea to solve your issue.

Related

MVC3 Route Using Parameter Name in URL

I have these routes:
routes.MapRoute("ListPage", "{controller}/{action}/{pn}/{ps}", new { controller = "home", action = "index", pn = 1, ps = 10 });
routes.MapRoute("Default", "{controller}/{action}/{id}", new { controller = "home", action = "index", id = UrlParameter.Optional });
Which allows me to have URLs like:
/foo/bar/1/10
to control lists of foos on a page (page 1, with 10 items a page). Hooray!
However, the following gives a 404:
/foo/bar/1
Using Url.Action("bar", "foo", new { id = 1}) gives the URL
/foo/bar?id=1
Which then matches correctly to the action signature
public ActionResult Bar(int id) { //stuff }
My thinking is that the first route in the table would not match, as both {pn} and {ps} are required.
So it drops to the second route, which should then match the parameter as {id}.
Obviously my thinking is not correct!
Question is: why is the route not matching without the parameter name?
Just try with interchanging routes postition
routes.MapRoute("Default", "{controller}/{action}/{id}", new { controller = "home", action = "index", id = UrlParameter.Optional });
routes.MapRoute("ListPage", "{controller}/{action}/{pn}/{ps}", new { controller = "home", action = "index", pn = 1, ps = 10 });

ASP.NET MVC basic routing with parameters

I have been trying to learn ASP.NET MVC 3 and things are going well apart from the routing aspect, whatever I try I just can't seem to get them quite right.
I have an ActionLink on the main page:
#Html.ActionLink("Contracts", "List", "Contract",
new { User.Identity.Name, page=1 })
Which is meant to access this method in the ContractController:
public ViewResult List(string user, int page = 1)
{
//snip
}
My routes are:
routes.MapRoute(
null,
"Page{page}",
new { Controller = "Contract", action = "List" }
);
routes.MapRoute(
null,
"Page{page}",
new { Controller = "Contract", action = "List", user = "", page = 1 }
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
The link now will return a 404 error as it can't find the action 'List' in the controller 'Home', which obviously means it didn't use either of the first routes.
Everything worked before I tried to add parameters to the ActionLink, so basically, what am I doing wrong?
Thanks very much.
Alex,
You're doing all the other bits absolutely correctly, however the actionlink has a missing parameter, try this for your actionlink:
#Html.ActionLink("Contracts", "List", "Contract",
new { User.Identity.Name, page = 1 }, null)
Adding the null as the final param (htmlAttributes) is all that's missing for you in this scenario (there are 9 overloads for Html.ActionLink, so it's VERY easy to miss the correct implementation).

Routing - Area Controller/View with parameter

Super simple MVC site with an Area to handle mobile devices. All of my Area routing works fine with the exception of a view that expects a parameter.
In the "normal" site I have a view video page that expects a parameter.
mysite.com/Video/123456
This works perfectly. After fighting this for a bit in my Area for the mobile content I have even gone down to using the exact same code/markup in my Controller and View. So I would expect that the following URL:
mysite.com/Mobile/Video/123456
Would resolve properly. It doesn't. I get a 404 (not found). If I take the parameter off:
mysite.com/Mobile/Video
It resolves properly.
I am sure this must be something I am doing wrong in the routing. Below is the appropriate section from my global.asax. Any help would be appreciated.
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Video", // Route name
"Video/{id}", // URL with parameters
new { controller = "Video", action = "Index", id = UrlParameter.Optional }, // Parameter defaults
new string[] { "mysite.Controllers.VideoController" }
);
routes.MapRoute(
"NewsItem", // Route name
"NewsItem/{id}", // URL with parameters
new { controller = "NewsItem", action = "Index", id = 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
new string[] { "mysite.Controllers.HomeController" }
);
routes.MapRoute(
"Mobile", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { area = "Mobile", controller = "Home", action = "Index", id = UrlParameter.Optional }, // Parameter defaults
new string[] { "mysite.Areas.Mobile.Controllers.HomeController" }
);
routes.MapRoute(
"Mobile/Video", // Route name
"Mobile/Video/{id}", // URL with parameters
new { area = "Mobile", controller = "Video", action = "Index", id = UrlParameter.Optional }, // Parameter defaults
new string[] { "mysite.Areas.Mobile.Controllers.VideoController" }
);
}
SteveInTN, you cannot have the same registration in both, Global.asax and MobileAreaRegistration.cs.
You only need to have Mobile Registration on MobileAreaRegistration.cs and call AreaRegistration.RegisterAllAreas() in Application_Start before RegisterRoutes(RouteTable.Routes).
If you want url like mysite.com/Mobile/Video/123456:
The mobile route registration should be in the format {controller} / {id}, like video route.
Registration in Global.asax:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Video", // Route name
"Video/{id}", // URL with parameters
new { controller = "Video", action = "Index", id = UrlParameter.Optional }, // Parameter defaults
new string[] { "mysite.Controllers.VideoController" }
);
//newsitem route
}
Registration on MobileAreaRegistration:
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"Mobile_default",
"Mobile/{controller}/{id}",
new { action = "Index", id = UrlParameter.Optional }
);
}
Looks like your Route name should not contain / since it may conflict with routing? When I do routing I make sure the names are unique and use underscores to represent separators like so : text_text. Not sure if this will work, worth a try though.

.NET MVC 3 trying to get RedirectToAction to follow the format of {controller}/{action}/{id}/{GUID}

I have to be missing something obvious here.
I would like to ensure all RedirectToAction follow the format of {controller}/{action}/{id}/{GUID} (e.g. http://www.mysite.com/report/edit/23/0975a566-983a-4414-962c-0ab1a921e89d
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
);
routes.MapRoute(
"Custom", // Route name
"{controller}/{action}/{id}/{GUID}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional, GUID = UrlParameter.Optional} // Parameter defaults
);
}
I am using the following in the controller:
return RedirectToAction("edit", "report", new { id = id, GUID = getGUIDFromId(id) });
However, I just get the following result:
http://www.mysite.com/report/edit/23?0975a566-983a-4414-962c-0ab1a921e89d
I have had a good search on this but I've found nothing about this particular issue (probably because it is obvious).
Many thanks in advance
Just reverse the order of your route definitions:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Custom",
"{controller}/{action}/{id}/{GUID}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional, GUID = UrlParameter.Optional }
);
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
Remember that the order in which you define your routes is important as they are evaluated in this same order by the routing engine. So you should always place specific routes before more general ones.

Routing without the controller name

I have a few controllers ,
One let say computer controller
It has action for laptop, desktop gadgets
i would like to have pages name :www.MyDomain/laptop (and so on )
and one let say electronic controller
it has action TV, DVD, (and so on )
i would like to have pages name :www.MyDomain/TV (and so on )
Without specifies the controller?
I don’t understand what happen to my question before I can't edit
(I hope the admin will delete it )
You could do this by specifying route constraints:
routes.MapRoute(
"Computers",
"{name}",
new { controller = "Computers", action = "Index", name = UrlParameter.Optional },
new { page = "laptop|desktop" }
);
routes.MapRoute(
"Gadgets",
"{name}",
new { controller = "Electronic", action = "Index", name = UrlParameter.Optional },
new { page = "tv|dvd" }
);
Now /laptop and /desktop will be routed to the Index action of the ComputersController and /tv and /dvd will be routed to the Index action of the GadgetsController.
In your Global.asax.cs:
routes.MapRoute(
"ViewLaptop", // Route name
"/laptop", // URL with parameters
new { controller = "Computers", action = "Laptop" } // Parameter defaults
);
This should do it.

Resources