Tuesday, October 23, 2012

ASP.NET MVC – Get field Name and Id for Model properties

ASP.NET MVC provides a number of convenient HtmlHelpers for form elements which accept a Lamda Expression returning a Model property as their first argument. The key advantages of these HtmlHelpers is that they simplify value binding and guarantee compile-time type-safety for selected Model members.

Html.TextBoxFor(m => m.Request.Name)
Html.LabelFor(m => m.Request.Name)

Sometimes it is necessary to know what the generated field Name or Id will be elsewhere in the view, but unfortunately, there is no public method available to return these values.

The following HtmlHelpers accept a Model property expression and return the same field Id and Name strings which would be produced by calling the standard form helpers.

public static string GetFullHtmlFieldName<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression)
{
    return helper.ViewData.TemplateInfo.GetFullHtmlFieldName(expression);
}

public static string GetFullHtmlFieldId<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression)
{
    return helper.ViewData.TemplateInfo.GetFullHtmlFieldId(expression);
}

public static string GetFullHtmlFieldName<TModel, TProperty>(this TemplateInfo templateInfo, Expression<Func<TModel, TProperty>> expression)
{
    return templateInfo.GetFullHtmlFieldName(ExpressionHelper.GetExpressionText(expression));
}

public static string GetFullHtmlFieldId<TModel, TProperty>(this TemplateInfo templateInfo, Expression<Func<TModel, TProperty>> expression)
{
    return templateInfo.GetFullHtmlFieldId(ExpressionHelper.GetExpressionText(expression));
}

Thursday, October 11, 2012

Identifying browsers with JavaScript disabled

In this day and age, a user without JavaScript enabled is going to have an awful time on the web and, quite frankly, “graceful degradation” and similar no-JavaScript fallbacks are a waste of time. That being said, sometimes it’s still important to be able to identify visitors who choose to navigate your website without any JavaScript.

Active Approach

A common technique for detecting whether a user has JavaScript enabled is to use JavaScript to set a form value and then check that value on the server after submission. While this is a valid approach, it’s not always ideal because it requires that some kind of interaction takes place on the client.

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
    $(function() {
        $('#jsEnabled').val('true');
    });
</script>

<form>
    <input type="hidden" id="jsEnabled" name="jsEnabled" value="false" />
    <input type="submit" />
</form>

Passive Approach

Another technique, and the one we use at ScoreBig.com, is to leverage the <noscript /> tag. <noscript /> identifies any block of code which should be rendered when JavaScript is not enabled and it is supported by all major browsers. By placing a request to an image resource on our server in a <noscript /> block we can infer that any a request made to that resource is with a browser with JavaScript disabled. The best part about this approach is that it requires no action by the user; the browser does all of the work.

<noscript>
    <img src="__nojs.gif" width="1" height="1" style="display: none" />
</noscript>

Monday, May 7, 2012

C# Truncate String - Whole Words

This is an update to my original string truncate helper which can be set to respect whitespace when terminating a string. This version will start at the character index specified as max length and then iterate back to the first instance of whitespace (if it exists), thus keeping whole words intact.

public static string Truncate(this string str, int maxLength, bool onlyOnWhiteSpace = false, bool appendEllipses = false) {
    if (str == null || maxLength >= str.Length)
    {
        return str;
    }

    if (onlyOnWhiteSpace
        && !char.IsWhiteSpace(str[maxLength])
        && str.Substring(0, maxLength).Any(char.IsWhiteSpace))
    {
        for (; maxLength >= 0; maxLength--)
        {
            if (char.IsWhiteSpace(str[maxLength]))
            {
                break;
            }
        }
    }

    return str.Substring(0, maxLength) + (appendEllipses ? "..." : "");
}