views:

105

answers:

1

I want to use a MVC HtmlHelper similar to LabelFor.

When using reflector on the code for this helper, I found the following code:

public static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html,       Expression<Func<TModel, TValue>> expression)
{
    return LabelHelper(html, ModelMetadata.FromLambdaExpression<TModel, TValue>(expression, html.ViewData), ExpressionHelper.GetExpressionText(expression));
}

The function LabelHelper is as follows:

internal static MvcHtmlString LabelHelper(HtmlHelper html, ModelMetadata metadata, string htmlFieldName)
{
    string str = metadata.DisplayName ?? (metadata.PropertyName ?? htmlFieldName.Split(new char[] { '.' }).Last<string>());
    if (string.IsNullOrEmpty(str))
    {
        return MvcHtmlString.Empty;
    }
    TagBuilder builder = new TagBuilder("label");
    builder.Attributes.Add("for", html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(htmlFieldName));
    builder.SetInnerText(str);
    return builder.ToMvcHtmlString(TagRenderMode.Normal);
}

In the 3 line of the second code sample, there's a check to see if the metadata.PropertyName is null.

My question is: How can a propertyName by empty in this case?

I am using this because I have some code that looks like this, and I want to test it in a unit test.

+1  A: 

It cannot be null. But it can be an empty string, for example when metadata.DisplayName is an empty string.

marcind
how can the metadata.Displayname be an empty string ?
Jan
@Jan if you look at the `DataAnnotationsModelMetadataProvider` you can see that it sets the `DisplayName` property on a `DataAnnotationsModelMetadata` object instance by grabbing the value from an annotating `DisplayNameAttribute`. It's possible that you can use `[DisplayName("")]` as an annotation for your property.
marcind
When I take a look at the code : metadata.DisplayName can be "" by settings the display name: I can't see how a propertyname can be empty
Jan

related questions