mvc3 map routes - asp.net

I am looking to use the following urls and maps some routes accordingly
<domain>/Home/About
<domain>/Home/SiteList
<domain>/Site/<id>/ (this one is defaulted to the details view)
<domain>/Site/<id>/section1/ (this one goes to section1 route in the Site controller)
<domain>/Site/<id>/section2/ (this one goes to section2 route in the Site controller)
e.g.
<domain>/Site/london/siteinfo
The above are covered by
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
However, i also want to use the following routes
<domain>/Site/<siteid>/section1/controller/action (where controller gets data linked to the <siteid> and action is optional)
an example link would be:
<domain>/Site/london/siteinfo/manager (manager is a controller and will list managers for the site)
if have tried various routes and read various posts but could not find anything which was applicable to me.
Can anyone provide some help please?
Thanks
Rudy

Add one more route below "Default":
routes.MapRoute(
"MyRouteName", // Route name
"{controller}/{action}/{id}/{section}/{subsection}", // URL with parameters
new { controller = "Home", action = "Index", id= "", section= "", subsection = "" } // Parameter defaults
);

Related

How to pass a parameter in place of controller name in ASP MVC?

I would like to know about this.
As we already know, the first parameter to a URL in ASP MVC would be a controller name as in
http://www.somedomain.com/Home/Index
Here, Home is controller and Index is action.
So if some one wanted to pass a value to this URL, he would do so like
http://www.somedomain.com/Home/Index/abc-power-corporation
where abc-power-corporation is a string identifier for a registered organization.
This is pretty much simple and routine. But I would like to know if there is a way to use this URL.
http://www.somedomain.com/abc-power-corporation
so that the URL is much friendlier and easier.
This should take me to the profile of the desired company.
Yes, you can do this in RouteConfig.cs.
Replace this:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
With this:
routes.MapRoute(
name: "RetrieveById",
url: "{id}",
defaults: new { controller = "ControllerNametoUse",
action = "ActionNameToUse", id = UrlParameter.Optional }
);
Note that it wouldn't be all that advisable to use both of these at the same time because it would create ambiguity, but it's still possible to use both of them as long as Action is explicitly specified in the URL and you specify the RetrieveById first in RouteConfig.cs.
You could also add more specific routes to get around the ambiguity issue:
routes.MapRoute(
name: "Customers",
url: "Customers/{action}/{id}",
defaults: new { controller = "Customers", action = "Index", id = UrlParameter.Optional }
);
These would need to be specified before the RetrieveById route so that they take precedence.

ASP.NET MVC How can better filter my route?

I have added a new route to my routing table:
routes.MapRoute(
"ModuleRoute", // Route name
"Module/{href}", // URL with parameters
new { controller = "Module", action = "GetHtml" }// Parameter defaults
);
I need this route to match on the following url structure:
/module/123abc.html
The problem is it also matches on this structure
/module/Launch/123abc.html
Calling link :
<%: Html.ActionLink("Launch", "Launch", new { href = item.Href })%>
How do I stop that from happening? I want he second structure to continue to be matched by the default route. I thought that because the number of parameters are different that this would not be a problem.
How can better filter my route to prevent this?
Thanks!
i agree with Max Toro, i've done some testing and that URL doesn't match Module/{href}.
This:
<%: Html.ActionLink("Launch", "Launch", new { href = item.Href })%>
is actually hitting the default route. You see this if you change the default route to the below (note the id is changed to href
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{href}", // URL with parameters
new { controller = "Home", action = "Index", href = UrlParameter.Optional } // Parameter defaults
);
so, this proves it is falling through the first route since it gets a proper url (no querystrings)
what it is doing (when you have the usual default route with id) is that the controller and action are matched but the id isn't. This is OK - the route still matches but leaves off the id. All additional values, such as your href are appended as querystring parameters so you end up with:
module/Launch?href=123abc.html
The way to get around it is to add another route similar to the one above that uses href instead of id
something like:
routes.MapRoute(
"Launch",
"Module/Launch/{href}",
new { controller = "Module", action = "Launch", href = UrlParameter.Optional }
);

ASP.Net MVC 2 Area, SubArea and Routes

I have been looking around for a solution for my problem. Found alot of similar issues, but none of them led to a solution for me.
I am trying to register an Area within an Area. This works however it "partially" screws up my routing.
My route registrations in the order they are registered, consider the FooBar and Foo registrations to be coming from AreaRegistrations
routes.MapRoute("FooBar_default",
"Foo/Bar/{controller}/{action}",
new { area = "Foo/Bar", controller = "Home", action = "Index"},
new[] { BarHomeControllerType.Namespace }
);
routes.MapRoute("Foo_default",
"Foo/{controller}/{action}/{id}",
new { area = "Foo", controller = "Start", action = "Index", id = UrlParameter.Optional },
new { controller = new NotSubArea()},
new[] { typeof(StartController).Namespace }
);
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute("PagesRoute", "Pages/{action}", new { controller = "Pages", Action "Index" }).DataTokens["UseNamespaceFallback"] = false;
routes.MapRoute("Default", // Route name
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
new[] { typeof(HomeController).Namespace }
).DataTokens["UseNamespaceFallback"] = false;
Now the following problem occurs. When going to Website/Foo/ or Website/Foo/Bar links in those pages are generated correctly using:
!{Html.ActionLink<HomeController>(c => c.Index(),"Home", new { area = "Foo/Bar"})}
or
!{ Url.Action("Index", "Home", new { area = "Foo/Bar"}) } //or a different area
However when i use this in my main pages, in other words Website/ or Website/Home etc..
!{Html.ActionLink<HomeController>(c => c.Index(),"Home", new { area = ""})}
or
!{ Url.Action("Index", "Home", new { area = ""}) }
//or with no area identifier specified
It generates the Url: Website/Foo/Bar/Home etc... Which ofcourse is wrong.
When i remove the Area registration for Foo/Bar it all works again. Going to the urls Website/Home/About or Website/Home directly does display the right pages, so im guessing somehow the internal UrlHelper is picking the wrong routes to render.
I tried switching the order of the FooBar_default and Foo_Default routes, so that the Foo_default route is registered before the FooBar_default route, but then the area does not work anymore (resource not found) and the links are still generated incorrectly.
What i find most odd is that removing the Foo/Bar registration solves the problem. I was hoping someone could shed some insight on this matter..
What you need to understand that an Area is just a routing concept which Microsoft have neatly wrapped up the concept or UrlRouting to get people started.
You can actually get the MVC framework to route your request however you like according to your requirements.
What you might need to look at doing, is writing your own RouteHandler. This will enable you to correctly direct how the MVC framework routes any request accoring to your requirements.
See this answer to asp.net mvc complex routing for tree path as an example to get you started.
chris166 outlines that my implementing your own IRouteHandler, and mapping your route to use that instead should get you what you need. Its a bit more effort than using out the box solution of areas, but should get you better results.
routes.MapRoute(
"Tree",
"Tree/{*path}",
new { controller = "Tree", action = "Index" })
.RouteHandler = new TreeRouteHandler();

Default value for parameter in Controller Method is overriding everything

Hello i have just started learning mvc2 and im having a problem with the default value for the parameter page(you can see the method below).
Its always 0 regardless of what i type in the URL. For example this
h.ttp://localhost:52634/Products/List/2
should show page 2 but when in debug mode the page parameter is 0, so im always getting the first page of the list in my view.
i am using the predefined standard routes in global asax when you start a new mvc2 project.
am i missing something?
//This is the ProductsController
public ViewResult List(int page = 0)
{
var products = productsRepo.Products()
//send in source, current page and page size
productList = new PagedList<Product>(products, page, 10);
return View(productList);
}
It's a routing issue, the default route specifies an id property, you're using a property called page. I'm new to MVC myself, but add this route before the default route:
routes.MapRoute("MyRoute", "{controller}/{action}/{page}",
new { controller = "Foo", action = "List", page = UrlParameter.Optional });
Remove the " = 0", and do:
public ViewResult List(int? page)
{
int val = page.GetValueOrDefault(0);
And use val everywhere instead of page. That should work. If not, it's an issue with routing.
HTH.
I know it's very late to answer. As default route for MVC is following
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
which is expecting that parameter name should be id. Now you have 2 options here either change your parameter name to id or the other option is define your own route in route.config file which is under App_Start folder.

How to hide controller name in Url?

How to hide controller name in Url?
I use the ASP.NET MVC.
The original url is: http://www.sample.com/Users.mvc/UserDetail/9615
The "Users" is controller name, the "UserDetail" is action name, and the "9615" is UserId.
How can I hide the controller name and action name in the url.
Just like this: http://www.sample.com/9615
I have writed the following code in the Global.ascx.cs to hide the action name:
routes.MapRoute(
"UserDetail", // Route name
"Users.mvc/{UserId}", // URL with parameters
new { controller = "Users", action = "UserDetail", UserId = "" } // Parameter defaults
);
Using the above code I hid the action name and got this url: http://www.sample.com/Users.mvc/9615
But how can I hide the controller name and get this url: http://www.sample.com/9615
Thanks.
The idea is the same. You do just the thing you did to the action. However, your problem arises from the fact that IIS is probably not mapping www.xyz.com/1234 to ASP.NET runtime. To do so in IIS7, enable integrated mode and in IIS6, add a wildcard mapping in handler map that maps everything to ASP.NET.
To add a wildcard map, see http://haacked.com/archive/2008/11/26/asp.net-mvc-on-iis-6-walkthrough.aspx (Search for "IIS6 Extension-less URLs" in that page)
After that, simply add a route:
routes.MapRoute("UserDetails", "{UserID}/{*name}",
new { controller = "Users", action = "UserDetail" , UserID=""});
This should do the trick.
MVC recognizes the difference between "{UserID}" and "{id}" so if you are going to have a route with only "{UserID}" in the Url you need to place it first in the list other wise it never gets hit. And make sure the default includes "id" since it will continually loop over "UserDetails" unless the default references id as apposed to UserID. I found this format works for me:
routes.MapRoute("UserDetails",
"{UserID}",
new { controller = "Users", action = "UserDetail", id = "" }
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Account", action = "LogOn", id = "" } // Parameter defaults
);

Resources