Make three-part route url for controller in ASP.NET MVC3 - asp.net-mvc-3

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.

Related

MVC3 :: Using global.asax to direct a specific controller/action to a different controller/action

In an MVC3 app I have a view in my home controller that is accessed via the following URL:
http://mysite.com/home/mycontent
However, my user wants to accees it via:
http://mysite.com/mycontent (without a specific reference to the home controller)
I've tried modifying my global.asax with the following:
routes.MapRoute(
"MyContent", // Route name
"MyContent", // URL with parameters
new { controller = "Home", action = "MyContent"} // Parameter defaults
);
But I get 404 errors when I try to use it. Is there a way I can accomplish what my user is wanting to do - redirecting a URL to a specific controller/view pair?
I think you should keep some "parameters":
routes.MapRoute(
"MyContent", // Route name
"{action}/{id}", // URL with parameters
new { controller = "Home", action = "MyContent", id = ""} // Parameter defaults
);
In what order are your routes registered? That route should come before your default route.
E.g.
routes.MapRoute(
"MyContent", // Route name
"MyContent", // URL with parameters
new { controller = "Home", action = "MyContent"} // Parameter defaults
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Pages", action = "Index", id = UrlParameter.Optional }
);
Otherwise, it should work... I have routes defined exactly the same as that.

Hierarchies in MVC3

Im working my way though an ASP.NET MVC tutorial and couldnt find the answer im looking for.
I understand that each controller class in the 'Controller' root folder is mapped to a Url, so:
****Controller Folder****
|- StoreController.cs
Maps to $url/Store
However, If I wish to creater a 'subfolder'
I.e. a Controller class located for $url/Store/Testing I cant seem to see how I go about it.
I tried deriving a class from StoreController.cs, but that didnt work.
URLs do not necessarily correspond to MVC application internal folder structure. You can use MVC routing tables to conceal the internal structure and redirect specific URLs to any controllers/actions you want. For example, you can create a TestingController.cs class in the Controllers folder and use this route in Global.asax:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Store-Testing", // Route name
"Store/Testing/{action}/{id}", // URL with parameters
new { controller = "Testing", 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
);
}
In this case, a request to http://[domain]/Store/Testing will be handled by TestingController.
That url would with the default route point to an action called Testing, within the Store controller.
You can however create your own custom routes in your global.asax file.

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/

MVC 3 Custom Url Routing

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.

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

Resources