How can i get an ID as parameter from an URL - asp.net-mvc

I want to route the following URL;
/anything/anything-v43243-anything
How can i route this to a specific controller and action with that id as parameter?
The text "anything" has to be a text with at least a few characters. The id needs to start with the letter "v".
I want this to create friendly URL's

You could write a custom route for that and appropriate constraints for the different parts:
routes.MapRoute(
"myroute",
"anything/{x}-{id}-{y}",
new { controller = "SomeController", action = "SomeAction" },
new { x = "[a-z]+", y = "[a-z]+", id = #"\d+" }
);

Related

Redirect To Action method not mapping correctly

I'm calling RedirectToAction but it isn't working properly.
I want the resulting URL to look like this:
https://localhost:44301/ManageSpaces/123/overview
but it looks like this and is missing the action portion of the URL:
https://localhost:44301/ManageSpaces/123
Here is my RedirectToAction call.
return RedirectToAction("overview", new RouteValueDictionary(
new {controller = "ManageSpaces", action = "overview", id = 123}));
Here is what my route looks like in RouteConfig:
routes.MapRoute("ManageSpaces",
"ManageSpaces/{id}/{action}",
new { controller = "ManageSpaces", action = "overview"},
new { id = #"\d+" } //The regular expression \d+ matches one or more integers
);
Maybe it is taking the default route. Rename, remove, or comment out the default route to see if that has any effect.
You have made your action route value optional by providing a default value. Optional values are ignored when resolving the URL.
routes.MapRoute("ManageSpaces",
"ManageSpaces/{id}/{action}",
new { controller = "ManageSpaces", action = "overview"},
new { id = #"\d+" } //The regular expression \d+ matches one or more integers
);
If you want to include the action in the URL, you have to make it a required argument.
routes.MapRoute("ManageSpaces",
"ManageSpaces/{id}/{action}",
new { controller = "ManageSpaces"},
new { id = #"\d+" } //The regular expression \d+ matches one or more integers
);

Routing and reflection problem

I added routing to my solution in order to have a more user friendly URL in the address bar.
I start the solution and when I rollover my Favorites link, I see the URL .../Affaire/Favorite (picture below). This one is OK for me.
When I rollover my Recycle bin link, I see the URL ../Affaire/Deleted (picture below). This one is OK for me.
Then I click on the Recycle bin link, I navigate to the corresponding page and the URL showed in the address bar is OK for me (picture below).
Next, I rollover the Favorite link again (picture below), I see the URL ../Affaire/Delete?OnlyFavorite=true!! That's not OK.
The routing is now retrieving an attribute not from my link but from the active URL! This attribute is named OnlyFavorite and I don't want this attribute. This is the "reflexion". Notice that all of my routes are using the same controller and the same action but using different attributes for the routes.
Below are some links I used.
Example for navigating to the favorite page:
#Html.ActionLink("Favorites", "SearchAffaires", new { OnlyFavorite = true })
Example for navigating to the recycle bin page:
#Html.ActionLink("Recycle bin", "SearchAffaires", new { StatusCode = "DELETED" })
Here are my routes:
routes.MapRoute(
"Affaire Status Open/Closed/Deleted", // Route name
"{controller}/{StatusCode}", // URL with parameters
new { action = "SearchAffaires" }, // Parameter defaults
new { controller = "Affaire", StatusCode = "^Open$|^Closed$|^Deleted$" }// Contraints
);
routes.MapRoute(
"Affaire Only Favorite", // Route name
"{controller}/Favorite", // URL with parameters
new { action = "SearchAffaires", Page = 1, OnlyFavorite = true }, // Parameter defaults
new { controller = "Affaire" } // Contraints
);
Do you have any idea how can I proceed to avoid this behaviour?
I don't want the routing to get the attribute named OnlyFavorite from my current URL by reflexion. I already try to pass OnlyFavorite=null on the action link but it doesn't work: the routing says "ok, I don't have a value for OnlyFavorite on the link itself but I have OnlyFavorite on the URL so I use it!".
When you are on the Deleted page, the link is being processed that way because the StatusCode token is equal to Deleted, so the first route is satisfied. Change your link as follows:
#Html.ActionLink("Favorites", "SearchAffaires", new { StatusCode = String.Empty, OnlyFavorite = true })
UPDATED
The best solution is to reverse your routes. As a general rule, the most specific routes should always go first, and you should have more generic routes later. Since the "Affaire Only Favorite" route is more specific, it should always go first. If it is the first route satisfied, that should address your issue.
UPDATE #2
I ran a test, and all of the links were generated correctly, when I set the routes as follows:
routes.MapRoute(
"Affaire Only Favorite", // Route name
"Affaire/Favorite", // URL with parameters
new { controller = "Affaire", action = "SearchAffaires",
StatusCode = String.Empty, Page = 1, OnlyFavorite = true } // Parameter defaults
);
routes.MapRoute(
"Affaire Status Open/Closed/Deleted", // Route name
"{controller}/{StatusCode}", // URL with parameters
new { action = "SearchAffaires" }, // Parameter defaults
new { controller = "Affaire", StatusCode = "^Open$|^Closed$|^Deleted$" } // Constraints
);
In addition, the following more generic routes also generated correctly:
routes.MapRoute(
"Favorite", // Route name
"{controller}/Favorite", // URL with parameters
new { action = "Search",
StatusCode = String.Empty, Page = 1, OnlyFavorite = true } // Parameter defaults
);
routes.MapRoute(
"Status Open/Closed/Deleted", // Route name
"{controller}/{StatusCode}", // URL with parameters
new { action = "Search" }, // Parameter defaults
new { StatusCode = "^Open$|^Closed$|^Deleted$" } // Constraints
);
For the more generic routes to work, I had to rename the action as Search and I had to change each link from SearchAffaires to Search.
Well, you could use Html.RouteLink helper to point exactly to the route used. However, as #counsellorben pointed out, you should set your more specific route to be the first one.
And if there's no problem to show your url like "Affaire/Favorite/True", then you can use the example below:
routes.MapRoute(
"Affaire Only Favorite", // Route name
"{controller}/Favorite/{OnlyFavorite}", // URL with parameters
new { action = "SearchAffaires", Page = 1, OnlyFavorite = ""}, // Parameter defaults
new { controller = "Affaire" } // Contraints
);

In ASP.Net MVC routing, how can you route 2 different paths that look the same, but have different types?

In ASP.Net MVC, I want 2 different routes:
http://mysite.com/foo/12345
and
http://mysite.com/foo/bar
In the class Foo, I have 2 methods that return ActionResult
public ActionResult DetailsById(int id)
{
. . . some code
}
and
public ActionResult DetailsByName(string name)
{
. . . some code
}
How do I set up 2 routes so that if the parameter is an int, it goes to DetailsById, but otherwise goes to DetailsByName?
You can use a route constraint for the first route.
routes.MapRoute("DetailsById",
"foo/{id}",
new { controller = "foo", action = "DetailsById" },
new { id = #"\d+" } // Parameter constraints
);
routes.MapRoute("DetailsByName",
"foo/{id}",
new { controller = "foo", action = "DetailsByName" }
);
The first route will only accept ids that match the regex (which accepts numbers only). If it doesn't match the first route, it will go to the second.
Use something like this:
routes.MapRoute(
"DetailsById",
"Foo/{Id}",
new {controller="Foo", action="DetailsById"},
new {Id= #"\d+" }
);
routes.MapRoute(
"DetailsByName",
"Foo/{Name}",
new {controller="Foo", action="DetailsByName"}
);
Remember that the routes are checked from top to bottom and stop at the first match.
I'm assuming that you already have a default route set up for your id parameter.
The only thing you will need to do is add a map route in your global.asax.cs:
routes.MapRoute(
"Foo_DetailsByName",// Route name
"Foo/DetailsByName/{name}",// URL with parameters
new { controller = "Foo", action = "DetailsByName", name = String.Empty } // Parameter defaults
);
In some cases, this can be accomplished through a route constraint. A common scenario is the ability to have my domain.com/482 behave the same way as my domain.com/products/details/482, where you do not want the 482 to be matched as a controller but as a Product ID.
Route constraints are regular expressions, though, so while you can use regex to match the pattern of the route, you are not actually matching based on data type.
See: http://www.asp.net/mvc/tutorials/creating-a-route-constraint-cs

Generic ASP.NET MVC Route Conflict

I'm working on a Legacy ASP.NET system. I say legacy because there are NO tests around 90% of the system. I'm trying to fix the routes in this project and I'm running into a issue I wish to solve with generic routes.
I have the following routes:
routes.MapRoute(
"DefaultWithPdn",
"{controller}/{action}/{pdn}",
new { controller = "", action = "Index", pdn = "" },
null
);
routes.MapRoute(
"DefaultWithClientId",
"{controller}/{action}/{clientId}",
new { controller = "", action = "index", clientid = "" },
null
);
The problem is that the first route is catching all of the traffic for what I need to be routed to the second route. The route is generic (no controller is defined in the constraint in either route definition) because multiple controllers throughout the entire app share this same premise (sometimes we need a "pdn" sometimes we need a "clientId").
How can I map these generic routes so that they go to the proper controller and action, yet not have one be too greedy? Or can I at all? Are these routes too generic (which is what I'm starting to believe is the case).
My only option at this point (AFAIK) is one of the following:
In the contraints, apply a regex to match the action values like: (foo|bar|biz|bang) and the same for the controller: (home|customer|products) for each controller. However, this has a problem in the fact that I may need to do this:
~/Foo/Home/123 // Should map to "DefaultwithPdn"
~/Foo/Home/abc // Should map to "DefaultWithClientId"
Which means that if the Foo Controller has an action that takes a pdn and another action that takes a clientId (which happens all the time in this app), the wrong route is chosen.
To hardcode these contstraints into each possible controller/action combo seems like a lot of duplication to me and I have the feeling I've been looking at the problem for too long so I need another pair of eyes to help out.
Can I have generic routes to handle this scenario? Or do I need to have custom routes for each controller with constraints applied to the actions on those routes?
Thanks
Add constraints to your routes by removing the null and replacing it with the constraint needed for that route:
For PDN, use a regular expression for digits:
routes.MapRoute(
"DefaultWithPdn",
"{controller}/{action}/{pdn}",
new { controller = "", action = "Index", pdn = "" },
new { pdn = #"\d+" }
);
For ClientID, use a regular expression for all characters:
routes.MapRoute(
"DefaultWithClientId",
"{controller}/{action}/{clientid}",
new { controller = "", action = "index", clientid = "" },
new { clientid = #"[A-Za-z]+" }
);
Since I don't keep the minutia of regular expression stuff in my head, I generally use a cheat sheet.
You should add some route constraints that say the PDN route matches numbers and the ClientId matches strings
I usually create a series of matches to use throughout my route declaration like so:
readonly static string ALPHA_MATCH = #"[\da-zA-Z]";
readonly static string DIGIT_MATCH = #"\d+";
then add the constraints to the routes like this:
routes.MapRoute(
"DefaultWithPdn",
"{controller}/{action}/{pdn}",
new { controller = "", action = "Index", pdn = "" },
new { pdn = DIGIT_MATCH }
);
routes.MapRoute(
"DefaultWithClientId",
"{controller}/{action}/{clientId}",
new { controller = "", action = "index", clientid = "" },
new { clientId = ALPHA_MATCH }
);

Creating urls with asp.net MVC and RouteUrl

I would like to get the current URL and append an additional parameter to the url (for example ?id=1)
I have defined a route:
routes.MapRoute(
"GigDayListings", // Route name
"gig/list/{year}/{month}/{day}", // URL with parameters
new { controller = "Gig", action = "List" } // Parameter defaults
);
In my view I have a helper that executes the following code:
// Add page index
_helper.ViewContext.RouteData.Values["id"] = 1;
// Return link
var urlHelper = new UrlHelper(_helper.ViewContext);
return urlHelper.RouteUrl( _helper.ViewContext.RouteData.Values);
However this doesnt work.
If my original URL was :
gig/list/2008/11/01
I get
gig/list/?year=2008&month=11&day=01&id=1
I would like the url to be:
controller/action/2008/11/01?id=1
What am I doing wrong?
The order of the rules makes sence. Try to insert this rule as first.
Also dont forget to define constraints if needed - it will results in better rule matching:
routes.MapRoute(
"GigDayListings", // Route name
"gig/list/{year}/{month}/{day}", // URL with parameters
new { controller = "Gig", action = "List" }, // Parameter defaults
new
{
year = #"^[0-9]+$",
month = #"^[0-9]+$",
day = #"^[0-9]+$"
} // Constraints
);

Resources