Tuesday, July 27, 2010

ASP.Net Helper Extensions

Been a while since I've put anything up here, so just tossing a few simple things here.
Helper Extensions! Holy cow things things are nice! Some of these aren't terribly well tested yet, and there should be more coming.

Capitalize

Found this somewhere where I can't remember. Acts like php's ucwords() function in that it takes a string "foo bar" and returns "Foo Bar"
public static string Capitalize(this String s)
{
    return s.ToCharArray().Aggregate(
        string.Empty,
        (working, next) =>
        {
            if (working.Length == 0 && next != ' ')
            {
                return next.ToString().ToUpper();
            }
            else if (working.EndsWith(" "))
            {
                return working + next.ToString().ToUpper();
            }
            else
            {
                return working + next.ToString();
            }
        });
}

Even/Odd

Simple enough and useful for zebra striping tables.
public static bool Even(this int i)
{
    return (i & 1) == 0;
}

public static bool Odd(this int i)
{
    return (i & 1) == 1;
}

Newlines

Useful for displaying input from textareas
/// 
/// Replace line breaks with <br /> tags and encode the output.
/// 
/// 
public static string Nl2br(this HtmlHelper html, string text)
{
    return html.Encode(text).Replace(Environment.NewLine, "<br />");
}

No comments:

Post a Comment