Creating A Simple DisplayFor Template In ASP.NET MVC

When building web applications, the DisplayFor and EditorFor HTML helpers are extremely useful to quickly build pages from your model. However, sometimes you would like a bit more control over their display.

For example, by default, boolean fields show as a disabled dropdown with the value selected. I would prefer to simply output the value – true or false – as plain text.

In order to replace the template used, first create a folder inside of the Shared folder under Views called DisplayTemplates.

Then create a partial view file matching the name of the data type, in this case Boolean.cshtml

Solution explorer with DisplayTemplate

Inside the Boolean.cshtml file, add the following code:

[csharp]
@model Boolean?

@(Model.HasValue? Model.Value.ToString() : "")
[/csharp]

That’s all you need to do. Any views that use DisplayFor on a boolean will pick up the new format automatically.

You can do a lot more than what is shown here. This is a pretty good guide to creating simple and advanced EditorFor templates. The same concepts apply for DisplayFor, just a different folder (DisplayTemplates vs EditorTemplates):

Extending Editor Templates for ASP.NET MVC

 

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/

How to Center a DIV with CSS

I often find that sometimes the smallest things that were simple in regular HTML are frustratingly complex in CSS. Take, for example, centering a div. You can float it right, float it left, but there is no center. Using text-align: center does not center it either, it just makes any text inside of it centered.

It turns out it is very simple to do. The key is that you must specify a width for your div, either using an exact pixel width, a percentage, or some other measure like em units. Once you set the width, you just have to add left and right margins set to auto, and the div will be centered inside of the container it is in.

Continue reading “How to Center a DIV with CSS”

Using HTML5’s Data Attributes With jQuery

While the HTML5 specification apparently won’t be finalized until 2014, you can use one of its more useful new additions, the data attribute, right now with jQuery for easy access to extra data.

When you are creating a dynamic page, you often need to store some additional data on an html element that will be used later when interacting with the page. Right now, developers often use non-existent class names or the rel attribute as a solution, or they add their own attributes, which is not valid HTML.

For example:

<img src="picture.jpg" largeimage="picturelarge.jpg">


<li rel="menu1">Menu item</li>

Browsers just ignore attributes they don’t support, so it has no negative effect. While this works, it is not the most elegant solution and is not valid HTML.


HTML5 introduces the data attribute to html elements. You can add multiple data attributes to an element. It works differently than other html attributes. The attribute begins with data, then has a dash and the name of the data item.

Example:

<img id="pic" src="picture.jpg" data-large="picturelarge.jpg"

data-productid="52" data-license="creative commons">

The img tag has three data attributes – large, productid and license. These can be accessed by getting the attribute, or by using the element’s dataset object. Each data attribute becomes a named property of the dataset object:

 
el.dataset.productid

Unfortunately, that method is not useable right now because of lack of browser support for the dataset object.
 
The solution is to use jQuery 1.43 or later, which has full support for the data attributes through the data() method. It does not rely on the dataset object, so it is compatible with non-HTML5 browsers.
 
Using the img example above, you can access the values of the data attributes like this:

$('#pic').data('productid') // 52


$('#pic').data('large') // picturelarge.jpg

While you could have just used the attr() to retrieve the value using the full attribute name ("data-productid"), the data() method is more elegant and readable, and has enhanced functionality. It can handle json encoded attributes, for example:

<li id='line1' data-options='{"color":"black","interior":"gray"}'>


Aston Martin</li>

The options attribute is automatically parsed by the data() method into named properties:

$('#line1').data("options").color //black


$('#line1').data("options").interior //gray

Data can also be added through code to an element with the data() method. It also has an event model that can be attached to for processing when data is read or set. For more info on data(), see the jQuery documentation on it.

jQuery provides an excellent way to start using HTML5 now without having to wait until browsers catch up.

 

 
 

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”