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
);
Related
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
);
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+" }
);
I would like to optimize the appearance of the URL like below:
http://localhost:3817/Affaire/SearchAffaires?OnlyFavorite=True
So I added a new route:
routes.MapRoute(
"Search Affaire Only Favorite", // Route name
"{controller}/{action}/OnlyFavorite", // URL with parameters
new { controller = "Affaire", action = "SearchAffaires", OnlyFavorite = true } // Parameter defaults
);
Now the URL is easier to read:
http://localhost:3817/Affaire/SearchAffaires/OnlyFavorite
But a new problem is occured: the other links on my page have changed because of the routing!
Example here: .../Affaire/SearchAffaires?LabelName=Baxter&OnlyLabel=True&OnlyFavorite=True
Before it was: .../Affaire/SearchAffaires?LabelName=Baxter&OnlyLabel=True
As you can see, the variable OnlyFavorite has been added to the URL. Finally I found the reason of this behaviour: the routing system is keen to make a match against a route, to the extent that it will reuse segment variable values from the incoming URL. The best way to deal with this behavior is to prevent it from happening. It is strongly recommend that you
do not rely on this behaviour, and that you supply values for all of the segment variables in a URL pattern.
That's a little bit annoying because I have a lot of variables!
Any solution on that problem? Why is that behaviour not happening whith one single route (the default one)?
Thanks
It looks like if I've registering routes like this, i get away from problem:
routes.MapRoute(
"Search Affaire", // Route name
"{controller}/{action}", // URL with parameters
new { controller = "Affaire", action = "SearchAffaires" } // Parameter defaults
);
routes.MapRoute(
"Search Affaire Only Favorite", // Route name
"{controller}/{action}/OnlyFavorite", // URL with parameters
new { controller = "Affaire", action = "SearchAffaires", OnlyFavorite = true } // Parameter defaults
);
I am a bit stuck on the design of my seo friendly urls for mvc....Take for example the following url:
http://myapp/venues/resturants.aspx?location=central&orderBy=top-rated
With my mvc app i have mapped it as follows:
http://myapp/venues/list/resturants/central/top-rated
{controller}/{action}/{category}/{location}/{order}
Now the only problem is that location and order are optional...so it should be possible to submit a request like: http://myapp/venues/list/resturants/top-rated . This proves to be a problem when the request hits the controller action, the location parameter has picked up "top-rated", naturally.
Any suggestions? I' am considering using explicit querystrings to handle more than one parameter but this is really my last option as i dont want to sacrifice SEO too much.
Has anyone eles run into such dilemmas? And how did you handle it?
Thanks in advance!
Click on your profile link and look at the URLs for Stats, Recent, Response, etc.
Examples:
https://stackoverflow.com/users/52065?sort=recent#sort-top
https://stackoverflow.com/users/52065?sort=stats#sort-top
with no sort it defaults to stats
https://stackoverflow.com/users/52065
Optional paramters should be query parameters
Assuming that the allowed values for location and order are unique (i.e. when they come in, you can tell them apart, or else if they only supply one, how are you going to know if it's a location or an order?), then you could just take two parameters and work out what they are in the controller.
Route: {controller}/{action}/{param1}/{param2}
Controller action:
public ActionResult MyAction(string param1, string param2)
{
string location;
string order;
if (!ParseLocation(param1, out location))
{ ParseLocation(param2, out location); }
// ...
}
Not particularly elegant, but does let you have the URLs you want.
You will always have this issue if you have multiple optional parameters. Either make one or both of them non-optional (and positioned earlier in the query string than the optional one) or use the querystring parameter notation.
ok guys just posting a solution i've been playing with so far.
I have set up my routes using constraints as follows:
routes.MapRoute(
"VenuesList",
"venues/list/{category}/{location}/{orderBy}",
new { controller = "venues", action = "list", category = "", location = "", orderBy = "" },
new { location = "central|east|west|south", orderBy = "top-rated|price" }
);
routes.MapRoute(
"VenuesListByLocation",
"venues/list/{category}/{location}",
new { controller = "venues", action = "list", category = "", location = "" },
new { location = "central|east|west|south" }
);
routes.MapRoute(
"VenuesListByOrder",
"venues/list/{category}/{orderBy}",
new { controller = "venues", action = "list", category = "", orderBy = "" },
new { orderBy = "top-rated|price" }
);
routes.MapRoute(
"VenuesListDefault",
"venues/list/{category}",
new { controller = "venues", action = "list", category = "" }
);
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
The idea is that if the validation fails it will go to the next route in the list...eventually hitting the default.
Needs some more testing but has worked well so far...
Why don't you create a property in the page for each possible querystring parameter?
This way you can handle it any way you choose with just a few lines of code...
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
);