Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/csharp-4.0/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net mvc 2 LabelforHtmlHelperMVC2:属性名称如何可以为空_Asp.net Mvc 2_C# 4.0_Html Helper - Fatal编程技术网

Asp.net mvc 2 LabelforHtmlHelperMVC2:属性名称如何可以为空

Asp.net mvc 2 LabelforHtmlHelperMVC2:属性名称如何可以为空,asp.net-mvc-2,c#-4.0,html-helper,Asp.net Mvc 2,C# 4.0,Html Helper,我想使用类似于LabelFor的MVC HtmlHelper 在此帮助器的代码上使用reflector时,我发现以下代码: public static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression) { return LabelHelper(html,

我想使用类似于LabelFor的MVC HtmlHelper

在此帮助器的代码上使用reflector时,我发现以下代码:

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));
}
publicstaticmvchtmlstringlabelfor(此HTMLHelperHTML,表达式)
{
返回LabelHelper(html、ModelMetadata.FromLambdaExpression(表达式、html.ViewData)、ExpressionHelper.GetExpressionText(表达式));
}
LabelHelper的功能如下所示:

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);
}
内部静态MvcHtmlString LabelHelper(HtmlHelper html、ModelMetadata元数据、字符串htmlFieldName)
{
string str=metadata.DisplayName??(metadata.PropertyName??htmlFieldName.Split(新字符[]{.'}).Last());
if(string.IsNullOrEmpty(str))
{
返回MvcHtmlString.Empty;
}
标记生成器=新标记生成器(“标签”);
Add(“for”,html.ViewContext.ViewData.TemplateInfo.getFullHtmlFieldDid(htmlFieldName));
builder.SetInnerText(str);
返回builder.ToMvcHtmlString(TagRenderMode.Normal);
}
在第二个代码示例的第3行中,检查metadata.PropertyName是否为null

我的问题是:在这种情况下,propertyName怎么可以为空


我之所以使用它,是因为我有一些代码看起来像这样,我想在单元测试中测试它。

它不能为空。但是它可以是空字符串,例如当
元数据.DisplayName
是空字符串时。

为什么要使用reflector来访问源?此处提供了完整的源代码(以及任何注释):@Jan如果查看
DataAnnotationsModelMetadataProvider
,可以看到它通过从注释
DisplayNameAttribute
获取值,在
DataAnnotationsModelMetadata
对象实例上设置
DisplayName
属性。您可以使用
[DisplayName(“”)
作为属性的批注。当我查看代码:metadata.DisplayName可以通过设置设置为“”时,显示名称:我看不出propertyname如何为空