Url.RouteUrl is adding wrong characters - c#

This is my routing configuration of my mvc3 application
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
// Parameter defaults:
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
As you can see this is the default routing of a mvc3 application and you can notice that I don't change it at all. So when I was tried to use the url helper RouteUrl like this
#Url.RouteUrl("Default",
new { Action = "RegistrarPago",
IDPago = ViewBag.IDPago,
confirmNumber = ViewBag.ConfirmationNumber },
Request.Url.Scheme)
The output is this
http://localhost/DescuentoDemo/pago/RegistrarPago?IDPago=60&confirmNumber=1798330254
This url it's wrong basically for this characters amp; What's wrong with the helper I'm assuming that's a encoding problem but why?

The # Razor function does HTML encoding by default. There's nothing wrong with the Url.RouteUrl helper. It's the context you are using it in.
It' as if you wrote the following in a Razor view:
#("http://localhost/DescuentoDemo/pago/RegistrarPago?IDPago=60&confirmNumber=1798330254")
You are outputting the result of it on an HTML page, so the correct thing to do is to HTML encode it. If you don't want to HTML encode then use the Html.Raw function:
#Html.Raw(Url.RouteUrl("Default",
new { Action = "RegistrarPago",
IDPago = ViewBag.IDPago,
confirmNumber = ViewBag.ConfirmationNumber },
Request.Url.Scheme))
And if you want to generate for example an anchor pointing to this url you directly use the Html.RouteLink helper in this case.

Related

Hide query string from URL asp.net c#

I have this following url:
http://www.example.com?user=Ana
and I want to get http://www.example.com?Ana
How can I get it?
You can route example.com/Ana to Home/Index with parameter (you can change controller and action to what is needed). Just add new route to your routing dictionary
routes.MapRoute(
"UserPage",
"{controller}/{action}/{user}",
new { controller = "Home", action = "Index", user = "" }
);
You can read more about routing here at ASP.NET
NOTE:
as Alexei Levenkov said it requires .Net MVC to route it that way.

ActionLink doesn't generate proper routing url for actions which has two parameters

In the view
#Html.ActionLink("Edit", "Edit", new { id = 1, year = 1 })
In the controller
// GET: /Forecasts/Edit/5
public ActionResult Edit(int id, short year)
{
...
}
It generated a url like
http://<localhost>/controllername/actionname/1?year=1
I would expect the actionlink generate a URL like :
http://<localhost>/controllername/actionname/?id=1&year=1
This url cannot be interpreted by MVC default routing, why the URL is not generated in the expected way? Thanks.
Update:
Now I found out it was a typo caused this problem for me, but the answer below is still good enough as it help me to further understand the way route works
You are using the default route, which will be formatted like this:
"{controller}/{action}/{id}"
Which means the first parameter will be id and will be written just after the /, without any named GET parameter.
If you want to have explicit parameters everywhere, just use this route configuration:
"{controller}/{action}"
If you remove the id all your parameters will be named.
I would expect the actionlink generate a URL like : http://<localhost>/controllername/actionname/?id=1&year=1
You cannot expect something like this if you are using the default route:
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
Get rid of the {id} from the if you expect such url pattern:
routes.MapRoute(
"Default",
"{controller}/{action}",
new { controller = "Home", action = "Index" }
);

Action Link to "lose" parameter

I've got the following routes:
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(null,"Conference/{shortName}/Submission/{submission}/{action}", new { controller = "Conference", action = "Show" });
routes.MapRoute(null,"Conference/{shortName}/{action}",new { controller = "Conference", action = "Index" });
routes.MapRoute("Default", "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
The following (hopefully obvious) links which are all working:
/Conference/testconf
/Conference/testconf/ShowSubmissions
/Conference/testconf/Submission/firstSub
/Conference/testconf/Submission/firstSub/EditSubmission
When I'm now in Submission/firstSub and create a ActionLink like this
#Html.ActionLink("Show Submissions", "ShowSubmissions", "Conference", new { shortName = Model.confereceShortName },null)
it creates the following Link
/Conference/testconf/Submission/firstSub/ShowSubmissions
How can i let the actionlink forget about Submission/firstSub without hardcoding it there?
Where do you have a placeholder for {controller}?
The default route should look like the following sample.
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{*id}", // URL with parameters
new {controller = "Home", action = "Index", id = UrlParameter.Optional} // Parameter defaults
);
Also try to remove the /Submission/ part in your first route.
Links for posts on custom route creation and ordering:
1) Creating Custom Routes (C#)
2) Custom routing for ASP .NET MVC
3) official source from asp.net mvc
Sometimes searching for 30min isn't enough, you gotta search 2h...
ASP.NET MVC 2 RC2 Routing - How to clear low-level values when using ActionLink to refer to a higher level?
Routlink or delete the values in the constraints.
For me Routelink does the job.
Although Thanks
ElYusubov & Aleksey

how do I add a url parameter to a routelink in asp.net mvc?

All, my situation is that I have the basic route, plus some other simple routes:
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = 1}
);
So the following url works: http://somesite.com/tags/index/1
However, some of my index pages take url parameters in the following fashion:
http://somesite.com/tags/index/1?when=lastmonth
How do I use Html.RouteLink to link to this?
You can't add '?' to routes in the global asax file like this:
routes.MapRoute("TagsWhen", "Tags/index/{id}?when={when}",
new {controller = "Tags", action = "Index", id = "", when = ""});
If this route worked I could link to it using:
Html.RouteLink(string.Format("{0} ", link.Rating), "LinksWhen",
new {id=link.ReferenceId, when=Model.When})
but it doesn't! So I'm not sure how I would use a Html.RouteLink to generate http://somesite.com/tags/index/1?when=lastmonth
Just found the solution myself. You can just do a regular Html.RouteLink and any object properties you don't have mapped to the url in global.asax it adds as a url parameter.
So using this route:
routes.MapRoute(
"Links",
"Links/details/{id}",
new { controller = "Links", action = "Details", id = ""} defaults
);
and this routelink:
Html.RouteLink("Link Text", "Links",
new {id=link.ReferenceId, when=Model.When })
generates the correct url:
http://localhost:2535/Links/details/1?when=onemonth
Matthew's approach probably didn't work because he needed another null parameter on the end, otherwise it passes the route values as html attributes. :)
<%= Html.ActionLink("Link text", "Index", "Home", new { id = 1, when = "lastmonth" }, null) %>
That last MapRoute() you came up with should work fine against it.
I don't have a computer able to test this, but off the top of my head
<%= Html.ActionLink("Link text", "Index", "Home", new { id = 1, when = "lastmonth" } %>
You don't need to specify optional parameters in your routes in the global.asax.cs file. Anything that doesn't match gets chucked into the query string by default.

How can I create a friendly URL in ASP.NET MVC?

How do I generate friendly URLs within the ASP.NET MVC Framework? For example, we've got a URL that looks like this:
http://site/catalogue/BrowseByStyleLevel/1
The 1 is Id of the study level (Higher in this case) to browse, but I'l like to reformat the URL in the same way StackOverflow does it.
For example, these two URLs will take you to the same place:
https://stackoverflow.com/questions/119323/nested-for-loops-in-different-languages
https://stackoverflow.com/questions/119323/
EDIT: The friendly part of the url is referred to as a slug.
There are two steps to solve this problem. First, create a new route or change the default route to accept an additional parameter:
routes.MapRoute( "Default", // Route name
"{controller}/{action}/{id}/{ignoreThisBit}",
new { controller = "Home",
action = "Index",
id = "",
ignoreThisBit = ""} // Parameter defaults )
Now you can type whatever you want to at the end of your URI and the application will ignore it.
When you render the links, you need to add the "friendly" text:
<%= Html.ActionLink("Link text", "ActionName", "ControllerName",
new { id = 1234, ignoreThisBit="friendly-text-here" });
This is how I have implemented the slug URL on my application.
Note: The default Maproute should not be changed and also the routes are processed in the order in which they're added to the route list.
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home",
action = "Index",
id = UrlParameter.Optional
} // Parameter defaults
);
routes.MapRoute("Place", "{controller}/{action}/{id}/{slug}", new { controller = "Place", action = "Details", id = UrlParameter.Optional,slug="" });
you have a route on the global.asax
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = ""}
// Parameter defaults )
you can define your own route like :
controller is the cs class inside the the controllers folder.
you can define your id - with the name you choose.
the system will pass the value to your actionResult method.
you can read more about this step here : http://www.asp.net/learn/mvc/tutorial-05-cs.aspx

Categories

Resources