Specify special case handler for MapRoute in ASP.NET MVC 3 - asp.net-mvc

I have the following Route defined in Global.asax:
routes.MapRoute(
"IncidentActionWithId", // Route name
"Incidents/{companyId}/{action}/{id}", // URL with parameters
new { controller = "Incidents" } // Parameter defaults
);
I have a special case of request, like this one:
/Incidents/SuperCompany/SearchPeople/Ko
In this case, action should indeed map to SearchPeople action, comapnyId to this action's parameter, but only when action is SearchPeople, the Ko should not be mapped to an id parameter of the action, but to searchTerm.
My action declaration is:
[HttpGet]
public ActionResult SearchPeople(string companyId, string searchTerm)
How can I achieve Ko to be mapped to searchTerm parameter in my action method?

You can define two routes, one with id and one with searchTerm if the id is supposed to be numeric (or you can specify regex constratints) and have different pattern to searchTerm.
See here how you can define constraints.
Example:
routes.MapRoute(
"IncidentActionWithId", // Route name
"Incidents/{companyId}/{action}/{id}", // URL with parameters
new { controller = "Incidents" }, // Parameter defaults
new {id = #"\d+"} // numeric only
);
routes.MapRoute(
"IncidentActionWithId", // Route name
"Incidents/{companyId}/{action}/{searchterm}", // URL with parameters
new { controller = "Incidents" }
);
NOTE
Define the one with constraint first.

Related

cant find Route when action has 2 params - Asp.Net MVC

I have a controller named Blog.
I have an action like this:
[Route("{code:int}/{title?}")]
public virtual ActionResult Index(int code, string title)
{
var postModel = _blogService.Get(code.ToUrlDecription());
return View(postModel);
}
I entered these urls, but all of them returned not found:
localhost:7708/Blog/index/12/post-title;
localhost:7708/Blog/index/12;
localhost:7708/Blog/12/post-title.
I tried to write a route like below, but the result was the same:
routes.MapRoute(
name: "showblogpost", url: "{controller}/{action}/{code}/{title}",
defaults: new {
controller = "Blog",
action = "Index",
title = UrlParameter.Optional
},
namespaces:new string[] { "Web.Controllers" }
);
One thing, you don't need to use both attribute [Route] on action and mapping route.
In your attribute [Route] you have specified only parameters, so route according to it should be localhost:7708/12
by route, specified in MapRoute it should be localhost:7708/showblogpost/12
What I suggest is - remove your attribute, name your route in MapRoute as you want to see in URL, and also you can remove "string title" parameter from action, as it's not used.

MVC 4: Multiple Controller action parameters

Instead of just {controller}/{action}/{id} is it possible to have mulitple parameters like
{controller}/{action}/{id}/{another id}?
I'm new to MVC (coming from just plain Web Pages). If not possible, does MVC provide a helper method like the UrlData availble in Web Pages?
You will just need to map the new route in your global.asax, like this:
routes.MapRoute(
"NewRoute", // Route name
"{controller}/{action}/{id}/{another_id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional, another_id = UrlParameter.Optional } // Parameter defaults
);
Then in your controller's action you can pick up the parameter like this:
public ActionResult MyAction(string id, string another_id)
{
// ...
}
Yes, you can define multiple parameters in a route. You will need to first define your route in your Global.asax file. You can define parameters in URL segments, or in portions of URL segments. To use your example, you can define a route as
{controller}/{action}/{id1}/{id2}
the MVC infrastructure will then parse matching routes to extract the id1 and id2 segments and assign them to the corresponding variables in your action method:
public class MyController : Controller
{
public ActionResult Index(string id1, string id2)
{
//..
}
}
Alternatively, you could also accept input parameters from query string or form variables. For example:
MyController/Index/5?id2=10
Routing is discussed in more detail here

ASP .Net MVC Routing without Controller and Action Name

simple question. I want something like:
http:/ /www.mywebsite.com/microsoft or http:/ /www .mywebsite.com/apple
so microsoft and apple should be like id but i use it just like controller in the default
this is the default route
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "index", id = UrlParameter.Optional } // Parameter defaults
);
This produce something like http:/ /www.mywebsite .com/home/aboutus or http: //www.mywebsite .com/products/detail/10
I added another route
routes.MapRoute(
"Partner", // Route name
"{id}", // URL with parameters
new { controller = "Home", action = "Partners"}, // Parameter defaults
new { id = #"\d+" }
);
but this has constraint that only allow numeric id.
how do I accomplish what I wanted.
thanks
If the expression can contain only letters and digits you could modify the constraint:
routes.MapRoute(
"Partner", // Route name
"{id}", // URL with parameters
new { controller = "Home", action = "Partners"}, // Parameter defaults
new { id = #"^[a-zA-Z0-9]+$" }
);
Not sure exactly what you are trying to achieve but it looks like you need a custom route constraint. Take a look here for an example:
http://blogs.planetcloud.co.uk/mygreatdiscovery/post/Custom-route-constraint-to-validate-against-a-list.aspx
Remember to register the route constraint first
If you don't want to provide a numeric constraint, just delete the 4th parameter, ie
routes.MapRoute("Partner", "{id}", new { controller = "Home", action = "Partners"});
The 4th parameter is an anonymous object that provides constraints for the route parameters that you have defined. The names of the anonymous object members correspond to the route parameters - in this case "controller" or "action" or "id", and the values of these members are regular expressions that constrain the values that the parameters must have in order to match the route. "\d+" means that the id value must consist of one or more digits (only).

URL Routing parameter name, order

Asking for the best way to address this issue:
in my controller I have the following action
public ActionResult Member(string id){return View();}
another action in the same controller
public ActionResult Archive(string year){return View();}
in my global.asax
routes.MapRoute(
"Archive", // Route name
"{controller}/{action}/{year}", // URL with parameters
new { controller = "Home", action = "Index", year = "" } // Parameter defaults
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id="" } // Parameter defaults
);
if I call this url mysite.com/archive/2009 this works because the action expecting parameter with a name "year" and the first route schema works with this request. But if I call this url mysite.com/member/john it will result in this url mysite.com/member?id=john
So it looks like if my first route in global.asax have the same construction but different parameter name, the one with the right parameter name will have the right url (mysite.com/archive/2009) but for the other won't. How can I solve this issue? I can change the route table to expect a generic parameter name like "param", but I need to change all the signature of the action to "param" as well and it is not very descriptive (param instead year or param instead id).
Try this:
routes.MapRoute(
"Archive", // Route name
"Home/Member/{id}", // URL with parameters
new { controller = "Home", action = "Member", id = "" } //
Parameter defaults
);
routes.MapRoute(
"Archive", // Route name
"{controller}/{action}/{year}", // URL with parameters
new { controller = "Home", action = "Index", year = "" } // Parameter defaults
);
You are allowed to use literals in the second parameter, and they will act as filters. The more specific your route is, the closer you need to put it to the top of the route configuration, the routing system will choose the first route that matches.
Here is a link to more detailed background information. Some of the syntax has changed since the article was written but the basic rules seem up to date.

ASP.NET MVC redirection Action to Default?

I have a action on my controller (controller name is 'makemagic') called 'dosomething' that takes a nullable int and then returns the view 'dosomething.aspx'. At least this is what I am trying to do. Seems no matter I get routed to the Default() view.
public ActionResult dosomething(int? id)
{
var model = // business logic here to fetch model from DB
return View("dosomething", model);
}
There is a /Views/makemagic/dosomething.aspx file that has the Inherits System.Web.Mvc.ViewPage
Do I need to do something to my routes? I have just the 'stock' default routes in my global.aspx.cs file;
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 = "" } // Parameter defaults
);
}
I am calling the action via a href like this in another page;
Click Me!
Seriously driving me nutso. Any suggestions on how to troubleshoot this? I attempted to debug break on my route definitions and seems a break there doesn't happen as one would expect.
Change it so the parameter isn't nullable so it will match the default route, or change the name to something other than id and supply it as a query parameter. An example of the latter would be:
public ActionResult dosomething(int? foo)
{
var model = // business logic here to fetch model from DB
return View("dosomething", model);
}
Click me
The it will work with the default routing implementation. Alternatively, you could do something that would distinguish it from the default route and then you would be able to have a route for it and not have to use query parameters.
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/foo/{id}", // URL with parameters
new { controller = "makemagic", action = "dosomething", id = "" } // Parameter defaults
);
Click Me!

Resources