MVC 3 Custom Url Routing - asp.net-mvc-3

I want to create a custom route, as a default mvc creates route like this:
domain.com/deals/detail/5
but in my case i want to create a custom route for it:
domain.com/delicious-food-in-paris
so it has to look for deals controller's detail action with passing an id value 5 to it.
how can i do it?
Thanks

This route maps all one segment urls to the detail method of the deals controller and passes one string argument called dealName to it:
routes.MapRoute(
null,
"{dealName}",
new { controller = "deals", action = "detail" }
);
But as AdamD have said, you should register that route as the last route in your setup because it will catch all urls which have only one segment.
With this approach you have to lookup your deal by name which might be not acceptable. So many apps use a hybrid approach and include the name and the id in the url like this:
domain.com/deals/5-HereComesTheLongName
Then you can use a route like this to get the id and optionally the name:
routes.MapRoute(
null,
"{id}-{dealName}",
new {
controller = "deals",
action = "detail",
dealName = UrlParameter.Optional
}
);

You can do this by defining a custom route in the Global.asax RegisterRoutes function. You would need to add this route after the default route so if the default controller action id pattern fails it will try to execute the final route.
An example would be to use the following:
routes.MapRoute(
"RouteName",
"/{uri}", //this is www.domain.com/{uri}
new { controller = "Controller", action = "ByUri" },
new { uri = #"[a-z\-0-9]+" } //parameter regex can be tailored here
);
After you register this route you can add a new custom controller to handle these routes, add the action that will handle this and accept a string as the parameter.
In this new action you can have a database lookup or some hardcoded valide routes that return Views.

Related

.NET MVC Routing works, except for one piece

Little help here and advice.
Working on my first MVC application and I've got an entity of Students setup.
Student Controller and views with basic CRUD capabilities.
mysite.com/Student gets me there.
Now I want to add Payments, so I've added a Payments controller and views with basic crud.
that gives me mysite.com/Payments
I want payments to go a URL that looks like: mysite.com/Student/Payments
So I researched URL routing and (I think) I had it backwards for a long time as nothing seemed to work. But now, I've created this additional Route:
routes.MapRoute(
"Payments",
"Student/Payments/{action}/{id}",
new { Controller = "Payments", action = "Index", id = UrlParameter.Optional }
);
And now it all seems to work properly. When I send an ActionLink to any action in the Payment controller, the URL is correct. For example: www.mysite.com/Student/Payments/Edit/5 comes up as the URL.
The problem I'm having is that Payments is still a base URL route. So I can also get to payments by going to www.mysite.com/Payments
How do I "remove" that route, so that mysite.com/Payments is not valid? Or am I doing this all ass-backwards in some way?
Any help appreciated.
Your kind of thinking about it the wring way around. The mapping configuration just supplies a hierachical list of rule to specify where a particular url's code lives.
So when you say it's still hitting mysite.com/Payments. That's because it's hitting the default rule in your Global.asax
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional} // Parameter defaults
);
You could remove this but then no default rules will work.
or you can add an ignore rule. In your case something like
routes.IgnoreRoute("Payments/{action}/{id}");
make sure you put this above the default rule.
You need to use overload of MapRoute method for your default route i.e.:
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index" },
new { controller = ""}); //there constraints for controller goes
Look at this blog post about creating custom constraints, there is example for "not equals"

MVC3 Url Routing to create member area

I would like to create a member area on my site with the following URL patterns:
Pattern for logged out user:
domain.com
domain.com/About
domain.com/Blog
domain.com/Blog/1 (where 1 is the post ID)
But I also have a member area where I prefix the Url with Member like this:
domain.com/Member/MyProfile
domain.com/Member/MySettings
This seems simple, but I can't see an obvious way to make routing rules for this. I have:
routes.MapRoute(
"Member", // Route name
"Member/{controller}/{action}/{id}", // URL with parameters
new { controller = "Task", 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
);
This works great for the member when you are logged in, but unfortunately the first rule also matches the logged out view and Url.Action("Blog", "Home") produces a Url that looks like this:
domain.com/Member/Home/Blog
How do I tell Url.Action that it must form Urls with the default rule outside the member area?
You could use a real MVC area instead of trying to simulate one. There's also a video you might checkout. The idea is that you leave your default route definition in Global.asax and then add a Member area to your site which will have a separate route configuration.

Incorrect Routing is ASP.NET MVC

I don't know why I have such problems with ASP.NET MVC routing. I wish there was a tool that showed me which routes I had currently setup. Regardless,
In my global.asax.cs file I have the following:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"SignUp", // Route name
"account/{controller}/{action}", // URL with parameters
new { controller = "Home", action = "Register" } // Parameter defaults
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
I have the following defined in HomeController.cs
public ActionResult Register()
{
return View();
}
I was expecting to be able to access this page by visiting /account/register in my browser. However, I continue to get a 404. What am I doing wrong?
/Account/Register matches your first route.
The word Register is matched to the {controller}, so it looks for a controller named RegisterController.
replace
routes.MapRoute(
"SignUp", // Route name
"account/{controller}/{action}", // URL with parameters
new { controller = "Home", action = "Register" } // Parameter defaults
);
with
routes.MapRoute(
"SignUp", // Route name
"account/{action}", // URL with parameters
new { controller = "Home" } // Parameter defaults
);
This will mean /account/register will route to the Register action on the Home controller. It will also mean that action links and other links you generate via #Html.ActionLink("Register", "Register", "Home") will generate the URL /account/register
Think of the 'URL with paramters' as a pattern that the URL will be matched against.
The problem with your original route map is that it is looking for a URL like this /account/controllername/actionname. So, when you go /account/register - it is taking register as the controller name, and taking the default action name (in this case register) - and as the 'register' action does not exist in the 'register' controller - you are getting a 404.
UPDATED
I updated my suggested route as per Robert's comments.
It is also worth noting, as Robert states, that this whole thing could be made more simple by making a 'Account' controller, and moving the 'Register ' action there. Then you could delete the 'SignUp' route, and just use default routing. If you thought about it, you'd agree that this would be a better place for a 'Register' action than the 'Home' controller.
Try using this nugget package http://nuget.org/packages/Glimpse.Mvc3
You can find more info about glimpse on http://getglimpse.com/

Controller not being properly activated

I have added a controller to my project named UserManager (automatically generated from the ado.net framework)
When I start the application, attempts to navigate to http://server/UserManager/ are met with a 404 error, but if I go to http://server/UserManager/Index the action is found and executes properly.
Is this a case of the controller not being called or is it just not treating index as the default action. Where are these properties set?
UPDATE
It seems that the problem derived from the fact that the default route is set to
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Permits", action = "ListApplications", id = UrlParameter.Optional }
This conflicts with the naming scheme for Usermanager (where the default is Index)
I struggled with ohow to add alternate routes that provided for default actions, but eventually figured out that the order of route addition determines which route takes the request (the earlier the route is added, the more chances it has to meet the criteria.)
Thanks
You need to ensure that the default route mapping specifies "Index" as the default action in your global.asax file.
Check that you have the following setting in your global.asax file:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
IN REPLY TO YOUR COMMENT:
Only by way of adding new route mappings. You also need to be aware that the first matching route mapping will be applied, so the order you specify the mappings in Global.asax is crucial.
For example, we wanted our FAQ controller to work with a URL http://domain/faq/{id} without the action specified in the URL, so we declared the following mapping before the default:
routes.MapRoute("Faq", "Faq/{id}", new { controller = "Faq", action = "Answer" });
In Global.asax.cs, check the default route is set up:
routes.MapRoute(
"Default",
"{controller}/{action}/{id}", new {
controller = "Home",
action = "Index",
id = UrlParameter.Optional}
);
Also, check that the controller is called UserManagerController, and derives from Controller

Make three-part route url for controller in ASP.NET MVC3

I am using ASP.NET MVC3 and curious about how to make routes like /Account/Ajax/Action map to controller AccountAjaxController method Action
Is there any way to do so?
Already solved issue using following code in Global.asax.cs file:
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new {controller = "Home", action = "Index", id = UrlParameter.Optional},
new[] {"MyProjectName.FrontEnd.Web.Logic.Controllers"}
);
routes.MapRoute(
"Ajax",
"Ajax/{controller}/{action}/{id}",
new[] {"MyProjectName.FrontEnd.Web.Logic.Controllers.Ajax"}
);
One way that I've done this is with RouteCollection.MapRoute(). See http://msdn.microsoft.com/en-us/library/dd470521.aspx. You can do all kinds of stuff with routes.
In the code below I would typically call this from my global.asax.cs Application_Start():
RouteCollection routes = RouteTable.Routes;
routes.MapRoute(
"ArbitraryRouteName", // Route name
"Account/Ajax/Action/", // URL with parameters
new
{
controller = "AccountAjax",
action = "Action"
}, // Parameter defaults
new
{
}
);
There are many ways to use this in order to generate links. You can use Html.RouteLink() in your views as an example. I believe that you can also call Html.ActionLink("link text", "AccountAjax", "Action"). I think that providing there is only one Route mapped to your controller and action name, ASP.NET MVC automatically figures out the proper URL to generate from your route mappings.
See http://msdn.microsoft.com/en-us/library/dd492585.aspx for an example of the RouteLink extension method.

Resources