ASP.NET MVC - Routes and UrlHelper - asp.net-mvc

I have the following route
routes.MapRoute(
"GigDayListings", // Route name
"gig/list/{year}/{month}/{day}", // URL with parameters
new { controller = "Gig", action = "List" },
new
{
year = #"^[0-9]+$",
month = #"^[0-9]+$",
day = #"^[0-9]+$"
} // Parameter defaults
);
When I visit the URL
gig/list/2009/01/01
This route matches perfectly and my action is called.
Inside my view I have a helper which does the following:
var urlHelper = new UrlHelper(ViewContext);
string url = urlHelper.RouteUrl(ViewContext.RouteData.Values);
The string generated is:
http://localhost:3539/gig/list?year=2005&month=01&day=01
Why is it not
http://localhost:3539/gig/list/2005/01/01
What am I doing wrong?

I think your problem is that you didn't specify the route name in your call. Try to use
UrlHelper.RouteUrl(**"GigDayListings"**, ViewContext.RouteData.Values);
overload with route name.
Cheers!

Have you checked that when you supply gig/list/2008/01/01 that it is actually using the GigDayListings route? Maybe it's using a different one

Related

Added a route and the behaviour changed

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
);

ASP.NET MVC RemoteAttribute: No url for remote validation could be found

How to configure RemoveAttribute to work with routes like this one?
context.MapExtendedRoute("ValidateSomething",
"some-where/validate/{propName}",
new { Controller = "SomeWhere", Action = "ValidateSomeRouteKey" });
When I pass above route name to RemoteAttribute constructor, an InvalidOperationException occurs. But works just like a charm when there is no propName in route definitions and parameter passed as querystring.
Thanks in advance;)
You need to add the {propname} parameter to your route, so that you can access it in your controller. In the example below I have made it optional.
context.MapExtendedRoute("ValidateSomething",
"some-where/validate/{propName}",
new { Controller = "SomeWhere", Action = "ValidateSomeRouteKey", propName = UrlParamter.Optional });

How can I pass the URL to the controller while routing ignores it?

Is there a way within asp.net MVC 2 whereby I can route a request and have a portion of the URL ignored and passed to the controller as a variable?
My needs state that I must store pages dynamically in a database, and they should be accessible by looking at the URL and reading the URL segments to find the relevant page. Effectively, I need a Site controller, to which the remaining portion of the URL will be passed.
Site-Controller/this/is/a/page
So this in case the site controller would pick up the /this/is/a/page 'string'
Is this possible?
Thanks!
Yes, use a wildcard route, like:
routes.MapRoute(
"SiteController", // Route name
"Site-Controller/{*url}", // URL with parameters
new { controller = "SiteController", action = "Index" }, // Parameter defaults
null // constraints
);
Then your action looks like:
public ActionResult Index(string url)
{
}
Create a wildcard Route in Global.asax which captures everything after the first segment of the url and passes it to your Action method:
routes.MapRoute("Page",
"Site-Controller/{*urlsegments}",
new {
controller = "Site-Controller",
action = "YourAction",
urlsegments = ""
});
Make sure your Action method accepts a 'urlsegments' parameter and you can work with it from there:
public ActionResult YourAction(string urlsegments)
{
// Do something with the segments here
}

Can I constrain a route parameter to a certain type in ASP.net MVC?

I have the following route:
routes.MapRoute(
"Search", // Route name
"Search/{affiliateId}", // URL with parameters
new { controller = "Syndication", action = "Search" } // Parameter defaults
);
Is there a way I can ensure "affiliateId" is a valid Guid? I'm using MVCContrib elsewhere in my site and I'm fairly it provides a way to implement this kind of constraint.... I just don't know what it is!
You could write regex constraints:
routes.MapRoute(
"Search", // Route name
"Search/{affiliateId}", // URL with parameters
new { controller = "Syndication", action = "Search" }, // Parameter defaults
new { affiliateId = "SOME REGEX TO TEST GUID FORMAT" } // constraints
);
I've never heard of this. I fear it would cause some confusion if you mistakenly used the wrong type for the affiliateId parameter in one of your action methods.

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