MVC Dynamic Action in Route - asp.net-mvc

Is it possible to define a route in MVC that dynamically resolves the action based on part of the route?
For example:
`/products/create/widget`
Would resolve to ProductsController.CreateWidget(Widget);
I want the route to be dynamic:
routes.MapRoute(
"Create",
"/products/create/{productType}",
new { controller = "Products", action = "Create{productType}" }
);
I need to have multiple Create actions that take in different model types but I don't want to add a new route every time I add one. Without appending the name to the action I get an ambiguous method error. Is it possible to do this?

I think you probably need to create your own custom route object derived from the RouteBase where you can assign action based on particular part of the Url. Take a look at this example.

Related

ASP.NET MVC Dynamic Action with Hyphens

I am working on an ASP.NET MVC project. I need to be able to map a route such as this:
http://www.mysite.com/Products/Tennis-Shoes
Where the "Action" part of the URL (Tennis-Shoes") could be one of a list of possibilities. I do not want to have to create a separate Action method in my controller for each. I want to map them all to one Action method and I will handle the View that is displayed from there.
I have this working fine by adding a route mapping. However, there are some "Actions" that will need to have a hyphen in them. ASP.NET MVC routing is trying to parse that hyphen before I can send it to my action. I have tried to create my own custom Route Handler, but it's never even called. Once I had a hyphen, all routes are ignored, even my custom one.
Any suggestions? Details about the hyphen situation? Thanks you.
Looking at the URL and reading your description, Tennis-Shoes in your example doesn't sound like it should be an action, but a Route parameter. Let's say we have the following controller
public class ProductsController : Controller
{
public ActionResult Details(string product)
{
// do something interesting based on product...
return View(product);
}
}
The Details action is going to handle any URLs along the lines of
http://www.mysite.com/Products/{product}
using the following route
routes.MapRoute(
null,
"Products/{product}",
new
{
controller = "Products",
action = "Details"
});
You might decide to use a different View based on the product string, but this is just a basic example.

ASP.NET MVC Routes: Conflicting action names with custom route

i all,
In a previous question, I asked how to define a custom route to handle the following URL:
http://www.example.com/User/Profile/Edit/{userProfileID}
I have a User object and a UserProfile object, but only a UserController that I want to be able to use for actions on both objects. I already have a method in UserController called Edit that handles edits on a User. But I also need a method for edits on a UserProfile. The answer to my routing question was the following route:
routes.MapRoute(
"ProfileleRoute", // Route name
"User/Profile/{action}/{userProfileID}", // URL with parameters
new { controller = "User", action = "Index" } // Parameter defaults
);
But given that custom route, where should I be declaring the edit action for a UserProfile, and what should it be called? It seems like I couldn't write another method in UserController called Edit because I already have one that handles User edits.
So I feel like I would end up with a need for two Edit actions to handle the following routes: "User/Edit" and "User/Profile/Edit". How do I get around this?
Thanks very much.
When the framework it's going to select what action to execute it first check the actions with the name required with a HttpPost ot HttpGet attribute that match the request, if not action is selected this way, then it select any action that match the name.
So, if you have two actions with the same name with no HttpPost or HttpGet attributes, you can't control with action is going to get executed.

Avoiding the Controller with Routing Rules in ASP.NET MVC

I've created a website with ASP.NET MVC. I have a number of static pages that I am currently serving through a single controller called Home. This creates some rather ugly URLs.
example.com/Home/About
example.com/Home/ContactUs
example.com/Home/Features
You get the idea. I'd rather not have to create a controller for each one of these as the actions simply call the View with no model being passed in.
Is there a way to write a routing rule that will remove the controller from the URL? I'd like it to look like:
example.com/About
example.com/ContactUs
example.com/Features
If not, how is this situation normally handled? I imagine I'm not the first person to run in to this.
Here's what I've done previously, using a constraint to make sure the shortcuts don't conflict with other routing rules:
routes.MapRoute(
"HomeShortcuts",
"{action}",
new { controller = "Home", action = "Index" },
new { action = "Index|About|ContactUs|Features" }
);
Add defaults for the controller names in the new statement. You don't have to have {controller} in the url.

How do you change the controller text in an ASP.NET MVC URL?

I was recently asked to modify a small asp.net mvc application such that the controler name in the urls contained dashes. For example, where I created a controller named ContactUs with a View named Index and Sent the urls would be http://example.com/ContactUs and http://example.com/ContactUs/Sent. The person who asked me to make the change wants the urls to be http://example/contact-us and http://example.com/contact-us/sent.
I don't believe that I can change the name of the controller because a '-' would be an illegal character in a class name.
I was looking for an attribute that I could apply to the controller class that would let me specify the string the controller would use int the url, but I haven't found one yet.
How can I accomplish this?
Simply change the URL used in the route itself to point to the existing controller. In your Global.asax:
routes.MapRoute(
"Contact Us",
"contact-us/{action}/",
new { controller = "ContactUs", action = "Default" }
);
I don't believe you can change the display name of a controller. In the beta, the controller was created using route data "controller" with a "Controller" suffix. This may have changed in RC/RTM, but I'm not sure.
If you create a custom route of "contact-us/{action}" and specify a default value: new { controller = "ContactUs" } you should get the result you are after.
You need to configure routing. In your Global.asax, do the following:
public static void RegisterRoutes(RouteCollection routes)
{
...
routes.MapRoute(
"route-name", "contact-us/{action}", // specify a propriate route name...
new { controller = "ContactUs", action = "Index" }
);
...
As noted by Richard Szalay, the sent action does not need to be specified. If the url misses the .../sent part, it will default to the Index action.
Note that the order of the routes matter when you add routes to the RouteCollection. The first matched route will be selected, and the rest will be ignored.
One of the ASP.NET MVC developers covers what Iconic is talking about. This was something I was looking at today in fact over at haacked. It's worth checking out for custom routes in your MVC architecture.
EDIT: Ah I see, you could use custom routes but that's probably not the best solution in this case. Unless there's a way of dealing with the {controller} before mapping it? If that were possible then you could replace all "-" characters.

How can I implement Dynamic Routing with my choice of URL format?

My URL requirement is countryname/statename/cityname. For this I'm writing my own RouteHandler and adding one new route into the routecollection like this:
routes.Add(new Route("{*data}",
new RouteValueDictionary(new
{
controller = "Location",
action = "GetLocations"
}),
new MyRoutehandler()));
Now my question is: How do I generate this type of URL?
I tried Html.ActionLink() but it's asking for an action name and controller name. However, in my URL format I don't have any action name or controller name. How do I solve this?
Is there a reason you can't just use the following with the built-in route handler:
routes.MapRoute("LocationRoute",
"{countryname}/{statename}/{cityname}",
new { controller = "Location", action = "GetLocations" });
That may conflict with the default "{controller}/{action}/{id}" route, but that would happen with your current system anyway (unless you make a custom Route, inheriting from System.Web.Routing.RouteBase, rather than a custom Route Handler). The Route Handler is for handling what to do AFTER the route data has been extracted. Since you're still using Controller and Action, you should still be able to use the MvcRouteHandler. If you want to customize how the Route Data is extracted, you probably want a custom Route.
Btw, if you want to use a route which doesn't involve Controller and Action names, use Html.RouteLink. ActionLink is just a wrapper which puts the controller and action into the RouteValuesDictionary and calls the same internal helper as RouteLink.
Although in this case, the route still has a Controller and Action ("Location" and "GetLocations"), so you can still use ActionLink. I think ActionLink lets you specify a Route Name, so if you give your route a name you can specify that name in ActionLink and it will use that route to generate the URL (I may be wrong about that and if so you can still use RouteLink and manually add the controller and action route values)

Resources