FriendlyURL : A new and exciting feature of ASP.NET

This is going to be the last post of 2012 by me. I am very happy that I am writing about a very exciting feature that is coming with ASP.NET.

I am really excited to learn and write on this. I really hated the ugly URLs and the extensions of the page that always visible when one opens the application unless and until you write your own custom url processor. With ASP.NET 4.0, Routing was introduced, which provided the capability to ASP.NET to have easier, manageable and SEO friendly urls, I wrote a post on it. You can click below to have a look on it.

URL Routing with ASP.NET 4.0

But that is little tidy to write. And it looks like writing extra code that does not produces any business functionality.

FriendlyURL as the name suggests gives a clean and SEO friendly URL.Currently it is available via NuGet and in pre release version.

So For this post, I have used my Visual Studio 2012 IDE. I created a new project as File-> New -> Website -> ASP.NET Empty Website.

Once the project got created. I require to install the NuGet for my application. So got to Tools-> Library Package Manager-> Package Manager Console

Package Manager Console

It opens a console then type Install-Package Microsoft.AspNet.FriendlyUrls -Pre and press enter as

FriendlyURL NugetInstallation

As you can see, I typed the command and can be seen in  the first red encircled area and press enter. It’ll install the NuGet and you can see the last red encircled area which shows FirendlyUrl is successfully added.

This can be used with two ASP.NET versions: ASP.NET 4.5 and ASP.NET 4.0.

Now you are ready for working with friendly URLs.

If you have  read the Readme.text. It gives a clear  idea how to start with. But I’ll take you through the steps. So let’s start

Step 1-> Add and Create a Class name preferably RouteConfig.cs ( You can have any name. I used MyRouteConfig.cs) and make it static. Also add the name space in the class Microsoft.AspNet.FriendlyUrls

Step 2-> Create a static Function in the class preferably named as RegisterRoutes with a Parameter of type RouteCollection and add  a line  routes.EnableFriendlyUrls() in the method as

public static class MyRouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.EnableFriendlyUrls();
    }
}

Step 3-> Add Global.asax file and add the following line in Application_Start as

  void Application_Start(object sender, EventArgs e)
    {
        MyRouteConfig.RegisterRoutes(RouteTable.Routes)
    }

Now you can start the development of your application. I have created two pages First.aspx and Second.aspx in my solution

That’s it. Now your code is ready for run.

First PageIf you see the above circled area in the above pic, it does not contain page extension (aspx). So now the url looks pretty. As an end user, I don’t care about the page extension and even some time it just irritates me.

Now if you want to redirect to another page, you can redirect by typing URL without page extension as

Response.Redirect("~\\Second");

There is one caveat here. You can not have a folder and Page with same name at the same level. If you have the name of a folder and the name of aspx page at same level, you would not be able to access the page without extension. So please keep it in mind.

Now you must have a question in Querystring. What will happen with Querystring?

You don’t need to worry at all. QueryStrings will work as earlier . Let’s have a look to the URL http://localhost:57353/First?Id=1001 then you can read the QueryString as below similar as earlier

string Id = Request.QueryString["Id"] as string;

Next point, if I have a URL say http://localhost:57353/First/Products/NewProduct and there is no page as NewProduct. What will happen It’ll open First.aspx.

But, How it works?

It starts from last segment (NewProduct) and will check if there is any NewProduct.aspx. If not then it moves to next segment and continue till it finds the exact aspx page.

Let’s explore more. Go to the server side of the page and include the namespace Microsoft.AspNet.FriendlyUrls. You’ll get bunch of methods that will be very useful at certain times.

  • Request.GetFriendlyUrlSegments() – It returns a collections of string which represents the URL segments. So if I have a URL http://localhost:57353/First/Products/NewProduct and the page exists First.aspx then it returns.
    URLSegments
    So you can see above, there is two segments and one can iterate through it. These url segments can be used to pass the values to a page via URL instead of QueryString. It also looks pretty.
  • Request.GetFriendlyUrlFileVirtualPath() – It returns the File virtual path. For the URL, discussed in the above example it will show as
    File Virtual Path
    You can see it shows the Virtual path of the file.
  • Request.GetFriendlyUrlFileExtension() -It returns the extension of the file. For the above url, it will be shown as File Extension
    As you can see, the extension of the page. As now with friendly url, the page extension is not shown. You can get the extension by the above method.

There are other important methods/features available that can be used to generate the URL etc. I’ll discuss some of those here

An available class FriendlyURL provides few static functions/properties that is very useful. Let’s see

  • FriendlyUrl.Segments ; Returns the segments of of the current URL similar as returned by Request.GetFriendlyUrlSegments()
  • FriendlyUrl.Resolve : This can be used to resolve the FriendlyUrl
    • FriendlyUrl.Href – It takes few parameters virtual path and list of url segments and generate the friendly URL out of it. And it is very useful while generating the URL in data binding and several other places. We can write
      FriendlyUrl.Href("~/First", "Product", 1001);
      

      And what it will return
      FriendlyURLgeneration

Hope you must have liked this new coming feature of ASP.NET. This will will let you get rid of aspx extension at URL , Frankly speaking, during my earlier days of career, I used to see the extension to check if the website is developed in asp.net.

I find this feature as one of the most of the exciting features of ASP.NET. Hope you all enjoy it and also like the post.

Enjoy and Love ASP.NET. And A very Happy New Year to all.
Cheers.
Brij

Advertisement

Client Ids generation with ASP.NET 4.0

From last sometimes, I started exploring ASP.NET 4.0 webforms enhancement. I really found some exciting enhancements in ASP.NET 4.0 and am sure, this all going to be make web development simple and will provide more flexibility to us.So I started picking the most exciting features of the ASP.NET 4.0 one by one.Earlier I wrote on URL Routing, you can go through to the link as below.

URL Routing with ASP.NET 4.0 [^]

As form the Title, you know that here I am going to discuss how we can control over generation of Client Ids of ASP.NET Server controls in ASP.NET 4.0. This Client Ids was another thing that was earlier mystery for me but later I identified the algorithm that is used to generate the the ClientIds for the server controls by the .NET engine,but they never been user friendly.

Why Client Ids:

Client Ids were always been problem for us.But as now a days, in new age application we are moving more towards the client side programming in new Rich Interent applications. Many new technologies and the way of programming has been evolved in last few years to make very rich UI like JQuery,JSon,Dojo.

In DOM, to access a a control client id play pivotal role.So Microsoft also trying to make our life easier by providing the capability to control over the client id generation which will ensure easy simple and less error prone RIA development.

Client Ids earlier:

So lets discus, how the ClientIds were generated earlier. First I’will statrt with normal control say textbox control or a label. So here the client Ids that are generated, was starting with prefix of all the naming containers from top to bottom with separated as underscore. And actually this was a good idea to generate the unique id at client side. But as I discussed ClientIds are key part of new age development. Lets look at the example for a simple textbox server control.My aspx looks like

So from the above picture we can see that my label and textbox are inside a contentplaceholder. Now lets look at the ClientId

Now here client Id is ctl00_ContentPlaceHolder1_myTextBox.If we go one by one the ctl00 is the counter ,next one is ID of contentplaceholder and next id of textbox.

So one thing as you move the control to some other part the Client Id will get changed as well.

So although we know the ID is going to be unique on the page but still you dont have any control over itFrown . .Net engine will generate the ClientIds according to its algorithm for you ).

So this all about of the simple controls, Now lets talk about some data controls, like gridview listwiew, dropdown etc. Here in these control what we do, we just bind the datasource to the control. And at runtime based on the data, the number of rows(controls) are generated. So what about the client Ids here. Here also the Client Ids are being generated in the same way as I already discussed with prefix of rownumber. So lets have a look to the example.

My aspx code for GridView. Here I am showing ID,Book Name and Price

So in the above example, I have taken a gridview. And in this I have three label in different ItemTemplates. The gridview is in contentplaceholder.

Now look to the ClientIds

You can see the id is like ctl00_ContentPlaceHolder1_gridviewBooks_ctl02_lblID. So here if we go one by one first the counter the contentplaceholder id again rowcounter generated in sequence for every row by .Net engine to make it unique and last lebel ID.

So  it becomes very uneasy to use.

But as new era web development, when we doing lots of work at client side the Client ids become a key part in web development.

Control Client Ids generation with ASP.NET 4.0:

ASP.NET 4.0 provides the power to control Client Ids generation. For that it provide the new property ClientIDMode property to handle this.This property enables us to to specify that, how the Client Ids will be generated for the controls . This provides four options:

  • AutoID
  • Static
  • Predictable
  • Inherit

We’ll discuss one by one.

AutoID:  this property is same as earlier version of .NET.Specify this value if you dont want any changes in the Client Id genration from the earlier version.As I discussed in ClientIDs in earlier versions.

Static: Means the you want the static id of your control.You should use this property when you know the ID will be going to be unique on the page. Here .net engine will generate the Client Ids as it is, without adding any suffixes or prefixes in it. This mode is mainly used for normal single control. Lets look at the example.

Here as you seen in the picture,I set the ClientIDMode for Label AutoID and for TextBox I set it Static. Now lets see the generated Client Ids

Now if you see the client ID of Label it is same as earlier one because here I set it Auto.

But for the TextBox I set it static. So here the Client Id is same as the ID that we set it on aspx page.This is the beauty of ASP.NET 4.0 . So if we set it static the .net engine wont generate a new client id for the control it will use the ID of the control as Client ID.

Note: One thing need to make sure here, if we set the mode static then there should be no control on the page with the same id because it will have the same client id on the page and it may be disastrous when we access it from Clientside.

Predictable: This is one another mode that I liked for the ClienId generation. When you exactly dont know whether the Id is unique on the page or not, then you can use this property.This value enables us the predict the client ids on the rendered page.When you set mode to this, you need to set some more proprties according to your own choice.

Now I will take the example as above.Now here the aspx code would be like

Here One thing we are using datacontrol then we can not set it static because there going to be multiple controls generated based on the data.

So here we will be using mode as Predictable so that we can predict what will be the id of the contrl. One more property ClientIDRowSuffix we need to set it here. I set it ID meand the ID column.

Now lets look at the generated Client Ids

Now here if we look at the ClientID . So here it is MainContent_gridviewBooks_lblName_1. So if look it deeply the we find that here there is no conter like thing. Here we have first id of contentplaceholder the id of gridview the id of label the the suffix id that we set. So its really predictable Smile and similarly for other rows.

Inherit: This is also value to set the to this property.As the name suggests,it means the Id genration of the contrl will be same as parent cpntrol. This is the default behavior of the control.

Setting the property at various levels:

There are various places where we can set the ClientIDMode property.This can be set at control level, page level as well as application. The behavior will be same. We can set it at page directive as below.

To set it at Application level, we need to set it in config file as

and that will be applied across all the pages in the application.

Feedback and Suggestions:

Feedback is key for improvement. I would request to you all to share your feedback and give me some suggestions, which which would encourage and help in more and quality writing.