Get the virtual url when using routing with webforms - asp.net

How do I get the virtual url and not the webforms page name that the url is mapped to when using System.Web.Routing with webforms.
I want the url "/confirm/5" and not "Confirm.aspx".

To get the routed URL for the page you are currently visiting, use Request.Url, as Pavel notes.
If you need to get the routed URL for a different page (such as when creating a hyperlink to another page), use the Page.GetRouteUrl method.
Here's a code snippet showing the use of Page.GetRouteUrl. It's from my article, URL Routing in ASP.NET 4:
lnkCategory.NavigateUrl = Page.GetRouteUrl("View Category", new { CategoryName = "Beverages" });
In the above snippet, "View Category" is the name of the routing rule I want to use. CategoryName is one of the routing parameters and I want to use the value "Beverages". The above call to Page.GetRouteUrl returns the string "/Categories/Beverages". (Of course, the exact string is returns depends on the routing rule "View Category" and the parameter values, but hopefully you get the idea.)

Try the following: System.Web.HttpContext.Current.Request.Url.AbsolutePath

Related

ASP.NET Routing optional first parameter

I am new ASP.NET Routing and have a question.
On the site I am developing, visitors sign up and create an account (with a display name), such as JohnDoe and the site personalises itself, with information pertaining to the display name.
For example (in order of the routing table, I currently have):
http://www.domain.com/ - Generic index page
http://www.domain.com/Page1 - Generic page1
http://www.domain.com/Page2 - Generic page2
http://www.domain.com/JohnDoe - Personalised index page
http://www.domain.com/JohnDoe/Page1 - Personalised page1
http://www.domain.com/JohnDoe/Page2 - Personalised page2
The above is working fine (I simply have a rule for every eventuality).
My problem is that, I now need to create asp:HyperLink controls on the pages of the site. Currently, I am using this:
NavigateUrl="<%$ RouteUrl:RouteName=ROUTENAME %>"
....in the tag of the HyperLink control
How can I, given the following addresses....
http://www.domain.com/Example - Generic example page
http://www.domain.com/JohnDoe/Example - Personalised example page
....match ROUTENAME, where the first parameter can be optional?
I could obviously create two routes, as follows....
Routes.MapPageRoute("Example_No_Displayname", "Example", "~/Example.aspx")
Routes.MapPageRoute("Example_With_Displayname", "{Code}/Example", "~/Example.aspx")
....but that means that the route names need to be different and I need to bind the Hyperlink control to match both of them.
I hope I have made myself clear and I appreciate any assistance the community may be able to give.
It would be somewhat atypical to put the username itself in the URL. The actual user identity/name would typically be extracted from some established security context/token, such as a cookie, so you could use the same URLs for both the anonymous pages and the personalized pages. Is there a specific reason you want to have the username in the URL?
You shouldn't need to match directly on the route name if you use the GetRouteUrl method. That way you can still use the two routes you need to make this work. See the full sample here.

RouteTable.Routes.MapPageRoute with optional parameter

I'm in an ASP.Net 4.0 web forms app.
I have this routing already in place in Global.asax and working:
RouteTable.Routes.MapPageRoute("status", "members/{userid}/{status}", "~/members/status.aspx");
The 'status' parameter will let me set active tab on the page to either status, blog, photos or about (default is status).
So when I post to: /members/status.aspx?userId=first.last
I'll see /members/first.last/status when the page loads.
What I need to do is render some links that will take user to the blog tab with a blog id so I can land on blog tab, which has multiple blogs displayed, and scroll to specific blog by id. I'm trying to set the href similar to how we do it in MVC: /members/first.last/blog/1000 (where 1000 is blog Id) - my other attempt is /members/first.last/blog/?id=1000 but I can never see the Id in the querystring keys in Page_Load.
I've tried adding this routing to no avail:
RouteTable.Routes.MapPageRoute("status",
"members/{userid}/{status}/{*queryvalues}", "~/members/status.aspx",
false,
new RouteValueDictionary { { "id", #"\d{4}" } });
Thanks for any assistance.
I think you should look in the items collection.
this.Context.Items["userid"]
or in RoutData collection for 4.0
Page.RouteData.Values["userid"]
see this link for info How to: Access URL Parameters in a Routed Page
Use as below:
routes.MapPageRoute(
"ProductsBrowse",
"browse/{BrowseBy}/{Category}/{*queryvalues}",
"~/Pages/Products/Browse.aspx"
);
Thx: asp.net webforms routing: optional parameters

ASP.net 4.0 Webforms Routing Postback Issue

We are using asp.net 4.0 and routing with web forms to create friendly urls.
The routing is working fine except that the correct "action" value is not being assigned to the form element in the master page for any route that has multiple levels.
For example, the route ( customer/{customerid} ) when browsed to with .../customer/12345 only displays 12345 in the "action" attribute of the form. The issue with this is that it isn't complete and any postback fails and gives an error "The HTTP verb POST used to access path is not allowed" If I updates the action as "customer/12345" (using Firebug), the postback works fine.
It even errors when using static routes like customer/customer, it only puts "customer" and not "customer/customer" as the action value of the form. Basically, only putting the last piece of the route into the action attribute instead of the whole route. Why?
Any ideas on how to correct this?
You can work around this by overiding the form action as form1.Action = Request.Url.PathAndQuery;]in the Page_Load event
See this related Topic.
It uses Request.RawUrl instead of Request.Url.PathAndQuery, which seams to return the same value.

MVC: capture route url's and pass them to javascript function

Short:Is there a way to have a route-definition that will pass the "CONTROLLER/ACTION" string value to a JavaScript function in stead of actually going straight for the controller action?
More:I have a masterpage which contains the navigation of the site. Now, all the pages need this navigation wrapped around it at all times, but because I didn't want the navigation to constantly load with each pagecall, I changed all my pages to partialviews.
These partial views are loaded via the JQuery.Load() method whenever a menu item is clicked in the navigation.
This all worked very good, up till now because I noticed it's also a requirement of the website to be able to link directly to page X, rather then default.aspx.
So, as an example:The main page is my "default.aspx" page, this utilizes my master page with the navigation around it. And each call to a new page uses a javascript function that loads that particular partial view inside a div that is known in my masterpage. So, the url never changes away from "default.aspx", but my content changes seemlesly.
The problem is, those url's also need to be available when typed directly into the address bar. But, they're partial views, so loading them directly from the address bar makes them display without any masterpages around them. Therefore my question if it might be possible to capture the route typed into the address bar and pass that on to my JavaScript function that will load that route in the content div.
(I hope I explained it ok enough, if not, feel free to ask more information)
You are 100% correct to not want to hard code your URLs in your javascript code as it demolishes one of the primary tenants of MVC to do so. I'm one of those "separation of concerns" guys who will not write a single line of javascript outside of a dedicated .js file so I cannot dynamically specify the URL the way tuanvt has. What I do is use MVCs Url.Action method to emit my service URLs into hidden inputs on the master page (or the specific page if it is not used in multiple places). Then my script file simply pulls the value out of that hidden input and uses it just fine.
ASP.NET MVC View Source
<input id="serviceUrl" type="hidden" value="<%= Url.Action("Action", "Controller") %>" />
JS Source
$.getJSON($("#serviceUrl").val(), function(data) {
//write your JS success code here to parse the data
});
First challenge, as you are using AJAX to load the partial pages you need client accessible URLs for the javascript to call. Second challenge, you need URLs that will load the HomeController and pass the 'page' portion of the URL into the javascript.
For the first aspect I'd create some abstracted routes, i.e. "/ajaxaccess/{controller}/{action}/{id}" for the partial pages. That would be the first registered route. A second route would accept any controller/action reference and always get processed by the HomeController Index action.
In the /Home/Index action you grab the requested URL and slice it up, take the /{controller}/{action}/... section and pass that into your default.aspx using TempData. In your page check for the existence of the TempData and if it exists use the value therein to trigger your AJAX page load for the partial page (don't forget that you'll need to prepend '/ajaxaccess' (or whatever you choose) to the URL before it's passed to your page.
I'm not going to provide code here as I think the information you'll gain from working through this yourself will be invaluable to you moving forward.
You could use hash anchor (#) on your url and read it with javascript.
var url = document.location.toString();
if (url.match('#')) {
anchor = url.split('#');
// do whatever with anchor[1] ..
}
You can do something like this, put this in your javascript code on the view:
var szUrl=<%= ViewContext.RouteData.Route.ToString()%>;
Then the current route will be stored on the variable szUrl.

url rewriting + Asp.Net Login Form = Death

on our site we do url rewriting to generate massive amounts of database generated pages. on every page, there is a Login control for users. like this:
Internal aspx page: /DB.aspx?id=123
User visible url: /ABC/123.aspx, /ABC/456.aspx ... (url rewritten)
unfortunately, the tag on each page has an action attribute of "DB.aspx?id=123". when the user clicks the button the browser is posting to /ABC/DB.aspx?id=123 which of course does not exist.
solutions i tried:
1. change the action attribute by subclassing HtmlForm. this destroys the all other forms on the site.
2. remove the action attribute (so that the browser is always posting to the same url). this works on the rewritten pages but on "/" (the default.aspx in the root dir) i get a message that the verb post is not allowed on "/" (iis 6 and i have no control over mappings)
anybody?
Check this really nice blog post from scott gu, http://weblogs.asp.net/scottgu/archive/2007/02/26/tip-trick-url-rewriting-with-asp-net.aspx.
"Specifically, you can take advantage of the new ASP.NET 2.0 Control Adapter extensibility architecture to customize the rendering of the control, and override its "action" attribute value with a value you provide. This doesn't require you to change any code in your .aspx pages"
Check the section: "Handling ASP.NET PostBacks with URL Rewriting", I have used the adapter he posted successfully.
Ps. be aware there are some issues on asp.net when using url rewrite when using cookieless session, and the rewritten url is deeper than the original page, just like the one you have. (/abc/apage vs. /db?). The issue is right into the source code of the framework, there are workarounds but that's a whole subject (with tradeoffs :( ... you might want to have them at the same level).
Semantics maybe, but does the action attribute = "DB.aspx?id=123" or "/DB.aspx?id=123"? Assuming your URL rewriting allows pass-through to physical pages, this might be your issue.
I never did it, but I saw the code using Reflector and I guess you can fix it this way:
On the page:
this.Form.Action = null;
or:
this.Form.SetAttribute("action", null);
If that doesn't work, just set the path you want:
this.Form.SetAttribute("action", "ABC/123.aspx");
If you upgrade to ASP.NET 3.5 SP1, the action property is now properly recognized and can be set from codebehind.

Resources