gpt4 book ai didi

asp.net-mvc-2 - Html.DescriptionFor

转载 作者:行者123 更新时间:2023-12-01 11:59:41 28 4
gpt4 key购买 nike

我正在尝试模拟“LabelFor”的 Html Helper 以使用 [Description] 属性。不过,我在弄清楚如何从帮助者那里获得属性(property)时遇到了很多麻烦。这是当前的签名...

class Something
{
[Description("Simple Description")]
[DisplayName("This is a Display Name, not a Description!")]
public string Name { get; set; }
}

public static MvcHtmlString DescriptionFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression);

最佳答案

这不是那么简单,因为 DataAnnotationsModelMetadataProvider(多好的名字!)不使用 Description 属性。因此,要使用 Description 属性,您需要执行以下操作:

  1. 创建自定义 ModelMetaDataProvider
  2. 将其注册为应用程序的元数据提供者。
  3. 实现 DescriptionFor 方法。

所以...这是自定义的 ModelMetaDataProvider:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.ComponentModel;

namespace MvcApplication2
{
public class DescriptionModelMetaDataProvider : DataAnnotationsModelMetadataProvider
{
protected override ModelMetadata CreateMetadata(IEnumerable<Attribute> attributes, Type containerType, Func<object> modelAccessor, Type modelType, string propertyName)
{
ModelMetadata result = base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName);

DescriptionAttribute descriptionAttribute = attributes.OfType<DescriptionAttribute>().FirstOrDefault();
if (descriptionAttribute != null)
result.Description = descriptionAttribute.Description;

return result;
}
}
}

现在,在 Global.asax 文件中的 Application_Start 方法中注册它,如下所示:

protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterRoutes(RouteTable.Routes);

// This is the important line:
ModelMetadataProviders.Current = new DescriptionModelMetaDataProvider();
}

最终,DescriptionFor 方法的实现:

using System.Linq.Expressions;

namespace System.Web.Mvc.Html
{
public static class Helper
{
public static MvcHtmlString DescriptionFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression)
{
ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);
string fieldName = ExpressionHelper.GetExpressionText(expression);

return MvcHtmlString.Create(String.Format("<label for=\"{0}\">{1}</label>",
html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(fieldName),
metadata.Description));// Here goes the description
}
}
}

这应该可以,我在我的机器上检查过。

谢伊。

关于asp.net-mvc-2 - Html.DescriptionFor<T>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2890318/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com