Using Extension Methods in a ASP.NET MVC Razor View

,

Extension methods were added in C# 3.0 and are a great way to add commonly used functionality to your projects in an object oriented way that cuts down on repetitive code. While extension methods are an underlying feature of C#, I am going to focus on their use in a view in an ASP.NET MVC project. The same principles apply to using them in any C# code..

I write a lot of ecommerce-related web applications, so I am constantly having to output prices formatted as currency. While I could just use the String.format method directly in a view, I prefer something a little more elegant and less repetitive. By adding a ToCurrency method to the decimal type, I can easily output a formatted string.

Start by adding a new class to your project with its own namespace, for example myproject.Extensions:

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace myProject.Extensions
{

 

Add a static class – this class will have methods added to it that will become your extension methods:

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace myProject.Extensions
{
    public static class Extensions
    {
    
    }
}

Each static method you add to the class will become an extension method. You tie it to a particular type by using the this keyword and a parameter of the type you want to extend:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace myProject.Extensions
{
    public static class Extensions
    {
        public static string ToCurrency(this decimal amount)
        {

            return String.Format("{0:C}", amount);

        }
    }
}

The ToCurrency method will be added to the decimal type because it is specified as the parameter type and includes the keyword this. I am simply passing the parameter to the String.Format method and returning a formatted string.

Calling the extension method either in other code such as a controller or within a view is simple. You just need to be certain to include the namespace in your class or view with a using statement. This is an example of it in a Razor view:

 

@model myProject.Models.Product
@using myProject.Extensions;

<span>@Model.Price.ToCurrency()</span>

The price property of the Product class is a decimal, so the method is available as if it were part of the underlying type.

You can add extension methods to any class the same way. Another example is providing a formatted address for an address object:

public static string GetFormatted(this Address address)
{
 string a=address.Name+"<br>";

if(address.Company!=null)
{
a+=address.Company+"<br>";
}
a+=address.Address1+"<br>";
if(address.Address2!=null)
{
a+=address.Address2+"<br>";
}
a+=address.City+", "+address.State+" "+address.Zip
return a;

}

Then, within a view, you can easily output a formatted address without having to put all the logic into the view:

@Model myProject.Models.Order
@using myProject.Extensions

<div>
@Model.BillingAddress.GetFormatted()
</div>

Since the BillingAddress property of the Order object is of type Address, the extension method is available as if it were a native part of the class. While you could add the method directly to the underlying class, if you are working with Entity Framework or a class you may not have the source code to, you can extend it without having to modify the original class.

While you could just as easily create a library of functions to call, extension methods provide a more elegant solution to code reuse and providing utility functions. The can even be put into a separate class library project to reuse them between projects.

For more information about Extension methods, see:

http://weblogs.asp.net/dwahlin/archive/2008/01/25/c-3-0-features-extension-methods.aspx
http://csharp.net-tutorials.com/csharp-3.0/extension-methods/

Creating Simple Text Notifications in Windows 8 with C#

Windows 8 introduces a much improved notification system that allows your applications to notify users in a variety of ways, from local application notifications to push notifications and badges on live tiles.

The simplest type of notification is a toast notification, which is a message that appears temporarily in the corner of the users screen and then fades away. Various applications have used them for notification of events like users signing on or off, messages received, etc. Windows 8 supports them at the OS level, so you can provide consistent notifications in your applications.

The notification system is in the Windows.UI.Notifications namespace, so the first step is to include the namespace in your code:

using Windows.UI.Notifications;

The notification templates are XML documents, so you also need to include the Windows.Data.Xml.Dom namespace:

using Windows.Data.Xml.Dom;

Creating the notification is simple. First, you use the ToastNotificationManager to get a template to work with for your notification. The GetTemplateContent method returns an XML document containing the template of the type you pass to the method as a ToastTemplateType value. In this case, we just need a simple text template, so we will pass it ToastText01:

XmlDocument x = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText01);

The Xml document that is returned looks like this:

<toast>
    <visual>
        <binding template="ToastText01">
            <text id="1"></text>
        </binding>  
    </visual>
</toast>

Pulling out the <text> element and appending a text node to it will set the text for the notification:

XmlNodeList toastTextElements = x.GetElementsByTagName("text");
toastTextElements[0].AppendChild(x.CreateTextNode("Copied to clipboard."));

Once the text is set, you create a ToastNotification object and pass the XML template to the constructor:

 ToastNotification toast = new ToastNotification(x);

Finally, you call the CreateToastNotifier method of the ToastNotificationManager and pass the ToastNotification object to the Show method to display it:

  ToastNotificationManager.CreateToastNotifier().Show(toast);

That’s all it takes. There are additional templates you can use that include spaces for images and formatted text. For more information on available templates, see http://msdn.microsoft.com/en-us/library/windows/apps/hh761494.aspx 

Make Content Panels Using jQuery

One common design problem is how to display a large amount of content on a page and still make it easily accessible. Often times, a table of contents is used at the top with links within the same page to sections below. This gets pretty unwieldy if you have a lot of content, and splitting it up into multiple pages can be annoying and hard to navigate.

An easy and elegant alternative is to use a dropdown list with content panels made of individual divs. The dropdown acts as the table of contents, and each time a selection is made, only that panel is displayed.

Example:

contentpanel

With a little bit of jQuery and CSS, it’s very simple to create this kind of ui.

Continue reading “Make Content Panels Using jQuery”

Creating a modal window with jQuery UI

A common need in a web application is to open a separate window to display some information or get input. As most modern browsers have popup blockers, it is difficult to use window.open reliably, and it also detracts from the user experience.

A better solution is to have a modal dialog that pops up within the same page over the current content. You see this very commonly on sites, and it is extremely easy to achieve with jQuery UI,  a library that adds rich UI elements to jQuery, such as dialog boxes, date and color pickers, buttons, sliders, and tabs.

Continue reading “Creating a modal window with jQuery UI”