How do I use an ActionLink with the RouteValueDictionary? - asp.net-mvc

I'm trying to make my URL look like this:
http://domain.com/controller/action/123/SomeTextForSEO
I tried using an Action Link, but that appends ?company=SomeTextForSEO instead of the company name after a slash.
<%: Html.ActionLink("DomainList", "Index", "DomainList", new { id = item.CompanyID, company = item.CompanyDisplayName.Trim() }, new object { })%>
and now I think I need to use a RouteValueDictionary but I'm unsure of how to do this in ASP.NET syntax. Can someone point me in the right direction? The MSDN examples are insufficient.

If you go to global.asax.cs and add a new route similar to the existing default route with the pattern
"{controller}/{action}/{id}/{company}"
Before the default one, you should find that the link will generate correctly with your ActionLink call as-is.
I'm on a phone so I'd like to be more verbose (a route restriction would be a good idea to prevent this route interfering with the default), but the HTC keyboard is not code friendly ;)

Related

Is there a simple way to map a single URL to another URL in ASP.NET MVC?

I have a working ASP.NET MVC application to which I would like to add a very simple URL which I would like to be redirected to another URL, without the Controller part of the path in it.
I.e. I want to be able to tell people to go to mySite.org/Hello and have it direct them to mySite.org/Whatever/WhateverElse?myfun=9, or whatever.
So I added a method in PublicController that redirects Hello to whatever, which works, except it requires me to tell people to go to mySite.org/PUBLIC/Hello, and we'd like to not have the extra word "public" in there.
Hours of confusing study later, I see that I could perhaps add a line in Global.asax.cs such as: routes.MapRoute(name: "Hello", url: "Public/Whatever"); ... or something... but that actually changes the way everything gets routed, and after trying various syntactical variations, nothing has seemed to just change one basic address to map to another basic address.
Is there a simple way to get mySite.org/Hello to map to another URL, without the virtual subdirectory for the public controller?
Create a custom route (it would need to be the first route in the table)
routes.MapRoute(
name: "Hello",
url: "Hello",
defaults: new { controller = "Whatever", action = "WhateverElse" }
);
then /Hello will redirect to /Whatever/WhateverElse

how can i ignore the timestamp that jQuery adds to the ajax url in my routing?

Edit: Sorry guys, but I wasn't seeing this behavior when I came into work the next day and couldn't reproduce it. Something else must have been going on. I was going to delete the question but you can't do that anymore. Since there aren't any upvotes anywhere, no harm done.
I'm pulling data in to a div via a jQuery ajax call. Since I'm using IE9 primarily, I need to disable output caching in jQuery using cache: false, on the ajax call. That produces a URL that looks like:
http://localhost/site/UserDetails.mvc/48d76cdd-da6f-414d-ba63-f24708d351ff?_=1315347866786
What I actually want is:
http://localhost/site/UserDetails.mvc/48d76cdd-da6f-414d-ba63-f24708d351ff
Note the ?_=1315 toward the end of the first one. I'm pretty sure that's a timestamp that jQuery is adding to prevent output caching. This is breaking my mvc routing, which is expecting a single ID field at the end of the route:
routes.MapRoute(
"DefaultNoAction", // Route name
"{controller}.mvc/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
So I'm getting a 404 for the URL that ends with the timestamp. I'm pretty new to MVC and I don't know how to tell the router that any url parameter that is named _ should be ignored. How would I do this?
Take a look at the ASP.NET MVC: url routing vs querystring thread, where discussed how to handle this case.
This is breaking my mvc routing, which is expecting a single ID field at the end of the route
No, this is not breaking anything on your routes. Query string parameters are not part of the routes. They are ignored.

ASP.NET MVC Appends ' ?RouteValueDictionary ' to my routes

I'm doing some changes on my routes, and suddenly the following is appearing in my url's as a querystring:
?RouteValueDictionary=System.Web.Routing.RouteValueDictionary
So, my url's now look like
http://localhost:20367/Search/AdvancedSearchResults?RouteValueDictionary=System.Web.Routing.RouteValueDictionary
How do I make it disappear?
I know the routing puts it in there, because it cannot find route values for the viewmodel that's passed along, but I can't seem to fix it...
I suspect your call to Html.ActionLink is picking the wrong overload. You might need to add an extra parameter at the end to force .NET to pick the right overload:
Html.ActionLink("click here, "SomeAction", "SomeController", routeValues, null)

I'm getting a "Does not implement IController" error on images and robots.txt in MVC2

I'm getting a strange error on my webserver for seemingly every file but the .aspx files.
Here is an example. Just replace '/robots.txt' with any .jpg name or .gif or whatever and you'll get the idea:
The controller for path '/robots.txt'
was not found or does not implement
IController.
I'm sure it's something to do with how I've setup routing but I'm not sure what exactly I need to do about it.
Also, this is a mixed MVC and WebForms site, if that makes a difference.
You can ignore robots.txt and all the aspx pages in your routing.
routes.IgnoreRoute("{*allaspx}", new {allaspx=#".*\.aspx(/.*)?"});
routes.IgnoreRoute("{*robotstxt}", new {robotstxt=#"(.*/)?robots.txt(/.*)?"});
You might want to ignore the favicon too.
routes.IgnoreRoute("{*favicon}", new {favicon=#"(.*/)?favicon.ico(/.*)?"});
You can adjust the regular expression to exclude paths.
Haacked from the source.
The ignore route given above didn't work for me but I found a similar one that did:
routes.IgnoreRoute("{*staticfile}", new { staticfile = #".*\.(css|js|gif|jpg)(/.*)?" });
This error could also happen if inside a view in your area, you use the Html.Action helper. This helper will always use the area as a prepend, unless you specifically tell it not to. E.g.,
#Html.Action("Main", "Navigation", new { area = string.Empty })
I found another solution too... While I don't think I'll use it, it's worth showing here in the answers:
The following should (in theory) ignore looking for controllers for anything with a '.' in it.
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" }, // Parameter defaults
new { controller = #"[^\.]*" } // Parameter contraints.
);
Do you still have:
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
... in your Global.asax.cs?
MVC puts it there by default, and it's supposed to handle this.
If you do, then the problem may be how you're mixing MVC and WebForms.
I encountered this error when I request resources that did not exist.
Specifically, I was requesting a custom IE css file:
<!--[if lt IE 8]>#Styles.Render("~/Content/ie7.css")<![endif]-->
(These are condition comments, interpreted by IE)
However, the actual resource existed on ~/Content/ie/ie7.css.
So, without any modifications to the routing, the error was solved by using the correct url of the resource.

UrlEncode of link ids with ASP.NET MVC HtmlHelper extension methods

I have actions that take string id parameters that are based on a username which can include characters that require encoding, for instance "user?1"
If I use ActionLink() to generate the links, passing the string without encoding, it generates a link like this: http:\\localhost\controller\action\user?1, and the action gets passed "user" as the id.
If I UrlEncode() the string before passing it to ActionLink, then the link generated is: http:\\localhost\controller\action\user%253f1 as ActionLink will then encode the '%' character for you. Besides this looking ugly, it then also generates a HTTP Error 400 - Bad Request when following the link which I've not yet tracked down the cause of.
Is there any way that I can generate the url like: http:\\localhost\controller\action\user%3f1?
How about removing the ? character or replacing it with something else like a dash (-) or underscore (_) ?
You should look in the Global.asax.cs file
add another route for your convenience, in this case, the ff. might work:
routes.MapRoute(
null,
"{controller}/{action}/user/{id}",
new { controller = "Home", action = "Index" }
);
I guess this is what you want, to separate action for each users, but i suggest you use cookie for this purpose.
PS: Remember to put that one on top of your default route since routing is trying to match from top to bottom.
you can create a jquery plugin that check all the links and replace the char that you need to replace with the new value.
and after apply this plugin to all the ActionLinks

Resources