ASP.NET MVC routing issue: How to allow "\" in id's - asp.net-mvc

I am using following route map
routes.MapRoute(
"RenderAssociatedForm",
"DoAction/{nodeLevelId}/{nodeSystemId}",
new {
controller = "FrontEnd",
action = "RenderAssociatedForm",
});
Now nodeLevelId can be anything like zs\bbal. As we know that we should escape '\', so we are using 'zs%5cbbal'. But still the following url is not mapping to this route.
//localhost/DoAction/zs%5cbbal/5
When I try simple Id without the escape character, it maps properly. Can anybody tell me where I am going wrong?

You could try it with two routes. The first route would be the one you showed, and the one after it would simply have "DoAction/{nodeLevelId}".

You'll need to use wildcards and parse the values out yourself:
routes.MapRoute(
"RenderAssociatedForm",
"DoAction/{*nodeLevelId}/{nodeSystemId}",
new
{
controller = "FrontEnd",
action = "RenderAssociatedForm",
});

#jfar probably has the best solution. Substitute the \ for a - or $ or something more URL friendly.

Related

How to make routelink return the correct URL?

here is the procedure to duplicate the issue.
start new mvc 4 project.
add the following lines to the RegisterRoutes() method just before the "Default" route
routes.MapRoute(
name: "Test",
url: "Test/{action}",
defaults: new { controller = "Test", action = "Index" }
);
add the following to Index.cshtml and About.cshtml
#Html.RouteLink("link to TestController", "Test")
As you can see that the generated html code is different for the 2 pages. I would expect the URL is "/Test" which is rendered correctly for Index.cshtml, but it become "/Test/About" for About.cshtml.
My question is if there is any documented way to generate the same correct URL. The above example is created just for demonstration purpose. I would like to use the routing table information to generate menu.
It seems the engine is setting the action route value from the current page ("Index", "About"). So one way to fix this is to "unset" that route value:
#Html.RouteLink("link to Test Controller", "Test", new { action = String.Empty })
Register your route
routes.MapRoute(
name: "TestUrl",
url: "Test",
defaults: new { controller = "TestController", action = "TestAction" }
);
add the following to TestAction.cshtml
#Html.RouteLink("Test", "TestUrl")
Now your URL is /Test, hoping this will help you.
Quickest way would be to just specify a blank action.
#Html.RouteLink("link to TestController", "", "Test")
This will produce /Test
For those who arrive here looking for .netcore razor page RouteLink syntax, don't use RouteLink's "page" reserved member. It will not work for the routeValues object as some have suggested. Instead, use the following format:
<a asp-page="RazorPage">RazorPage</a>
This handles trailing and the absence of trailing forward slashes. The RazorPage is the name of the page without any characters after the first ".".

How do I use an ActionLink with the RouteValueDictionary?

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

Routing *Path wildcard will not accept Path when only one slash

I have a problem with the wildcard route that I wonder if anyone can help on, I have a route as below
routes.MapRoute(
"ReportRoute",
"Report/{*path}",
new { controller = "Home", action = "Index"})
.RouteHandler = new ReportPathRouteHandler();
where the routehandler splits the path into its correct parts to get the correct report and this works great, if I put in a route www.mysite.com/report/folder1/folder2/report then I'll get what I'm looking for however my problem is if I have a link like www.mysite.com/report/folder1/report, the *path is only folder1/report and the routing really doesn't like this, in fact it doesn't even hit my route handler, just goes straight to 'resource can't be found' server error page. I tried to get around this by adding a new route before the wildcard as below
routes.MapRoute(
"ReportRoute2",
"Report/{path}/{name}",
new { controller = "Home", action = "Index" });
where the Controller takes Path and Name as two string parameters but still no joy, has anyone got any ideas or pointers as to what can fix this issue? Thanks for your help.
The first example should be fine (except that odd .RouteHandler = new ReportPathRouteHandler(); at the end). What does your controller action look like? Does it take a "string path" as a parameter?

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