Click here to Skip to main content
15,867,488 members
Articles / Web Development / ASP.NET

ASP.NET WebForms Can Do Friendly's Too!

Rate me:
Please Sign up or sign in to vote.
4.00/5 (1 vote)
14 Jan 2018Ms-PL3 min read 26.4K   6   3
In this article, I'll introduce the concept of FriendlyUrls in ASP.NET webforms. We'll see how to retrieve data from a formatted URL string so that it can be consumed. We'll also take a brief look at ValueProviders in ASP.NET 4.5 to present some data.

With the ASP.NET 4.5 release, we saw the addition of declarative model binding, value providers, unobtrusive validation, and model state. While some of these features were a carry over from the MVC framework, we were still missing that cool SEO friendly friendly URL format. With the release of ASP.NET 2012.2, Microsoft has delivered on that need.

The FriendlyURLs feature can be added to any ASP.NET WebForms 4 project through the installation of a NuGet package with the command:

Install-Package Microsoft.AspNet.FriendlyUrls -Pre

If you are not currently using routing in your webforms project, you will need to add a call to configure the routing. If you are familiar with MVC, you should recognize this snippet in global.asax.cs:

JavaScript
RouteConfig.RegisterRoutes(RouteTable.Routes);

The content of your RouteConfig.cs file in the App_Start folder should look something like:

JavaScript
public static class RouteConfig
{
  public static void RegisterRoutes(RouteCollection routes)
  {
    routes.EnableFriendlyUrls(new FriendlyUrlSettings()
    {
      AutoRedirectMode = RedirectMode.Permanent,
      CachingMode = CachingMode.Dynamic
    });
  }
}

I have added the configuration options to make redirects from the FriendlyUrl routes permanent (HTTP 301 status code) and then dynamically cache the contents of the output. With this configuration in place, I can now route my users to cool looking and SEO friendly URLs like:

I know what you're thinking: Jeff, in MVC, I get the entries from the request submitted through action methods as input parameters, how do I access these values from a webform? The implementation of FriendlyUrls includes an extension method for the Request object called GetFriendlyUrlSegments that returns an IList<string>. That's nice, if you really want to iterate over the entire URL and parse apart what was submitted, but I think there is something else you would prefer.

Enter the ValueProviders

ValueProviders are parameter-level attributes that can be used to decorate methods in your webforms. Using a FriendlyUrlSegments attribute, I can configure a public method in my webform to provide content based on the values submitted on the URL. Consider this simple webform:

I can use a new feature in ASP.NET 4.5 and bind my Product business object directly to the FormView control. All I need to do is specify the ItemType and SelectMethod properties to bind data for read operations. ItemType is the qualified name of the class that is being bound. SelectMethod is the public method in the code-behind that will return the business object (Product in this sample) to be presented. Note that I am using the Item keyword to bind to the Product. This creates a one-way binding, similar to how we use the Eval keyword. There is also a BindItem keyword available that performs the familiar two-way binding that the Bind keyword gives us.

Let's look at the GetProduct method:

JavaScript
public static readonly List<product> ProductList = new List<product>()
{
  new Product
  {
    Id=1,
    Name="Chess",
    Description="The classic game - you know... Chess!",
    Price=9.99M
  }
};

public Product GetProduct([FriendlyUrlSegments]int? id)
{
  if (id == null)
    return null;

  return ProductList.FirstOrDefault(p => p.Id == id.Value);
}

Now we see how the FriendlyUrlSegments value provider is put to use when the webform is rendered, at the time that my FormView is ready to bind to data. I don't need to fuss with event timings, postbacks, or viewstate. The webform will pass the parameters appropriately from the FriendlyUrl as an input parameter when the FormView is ready to be rendered. In this case, I end up with a simple webpage that tells me about the Chess product:

Summary

In this article, we introduced the concept of FriendlyUrls in ASP.NET webforms. I showed you how to retrieve data from the formatted URL string so that it can be consumed. We also took a brief look at ValueProviders in ASP.NET 4.5 and used the FriendlyUrls attribute with some declarative data-binding on a standard FormView to present some data.

Next time, we'll dig further into ValueProviders and ModelBinding in ASP.NET 4.5.

License

This article, along with any associated source code and files, is licensed under The Microsoft Public License (Ms-PL)


Written By
Program Manager
United States United States
Jeff Fritz is a senior program manager in Microsoft’s Developer Division working on the .NET Community Team. As a long time web developer and application architect with experience in large and small applications across a variety of verticals, he knows how to build for performance and practicality. Four days a week, you can catch Jeff hosting a live video stream called 'Fritz and Friends' at twitch.tv/csharpfritz. You can also learn from Jeff on WintellectNow and Pluralsight, follow him on twitter @csharpfritz, and read his blog at jeffreyfritz.com

Comments and Discussions

 
QuestionProblems to display mobile version with FriendlyUrls Pin
Licey23-Apr-14 2:28
Licey23-Apr-14 2:28 
AnswerRe: Problems to display mobile version with FriendlyUrls Pin
Jeffrey T. Fritz5-May-14 3:55
sponsorJeffrey T. Fritz5-May-14 3:55 
Can you share what your MasterPage markup code looks like?
GeneralRe: Problems to display mobile version with FriendlyUrls Pin
Licey21-May-14 5:39
Licey21-May-14 5:39 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.