如何从 ModelMetadata 检索 GroupName 数据注释

发布于 2025-01-08 00:54:31 字数 2405 浏览 4 评论 0原文

System.ComponentModel.DataAnnotations 中的 DisplayAttribute 有一个 GroupName 属性,它允许您在 UI 控件(例如 WPF/WinForms 中的属性网格)中对字段进行逻辑分组。

我正在尝试在 ASP.NET MVC3 应用程序中访问此元数据,本质上是为了创建属性网格。如果我的模型看起来像这样:

public class Customer
{
    [ReadOnly]
    public int Id { get;set; }

    [Display(Name = "Name", Description = "Customer's name", GroupName = "Basic")]
    [Required(ErrorMessage = "Please enter the customer's name")]
    [StringLength(255)]
    public string Name { get;set; }

    [Display(Name = "Email", Description = "Customer's primary email address", GroupName = "Basic")]
    [Required]
    [StringLength(255)]
    [DataType(DataType.Email)]
    public string EmailAddress { get;set; }

    [Display(Name = "Last Order", Description = "The date when the customer last placed an order", GroupName = "Status")]
    public DateTime LastOrderPlaced { get;set; }

    [Display(Name = "Locked", Description = "Whether the customer account is locked", GroupName = "Status")]
    public bool IsLocked { get;set; }
}

我的视图看起来像这样:

@model Customer

<div class="edit-customer">
    @foreach (var property in ViewData.ModelMetadata.Properties.Where(p => !p.IsReadOnly).OrderBy(p => p.Order))
    {
        <div class="editor-row">
            @Html.DevExpress().Label(settings =>
                {
                    settings.AssociatedControlName = property.PropertyName;
                    settings.Text = property.DisplayName;
                    settings.ToolTip = property.Description;
                }).GetHtml()
            <span class="editor-field">
                @Html.DevExpress().TextBox(settings =>
                    {
                        settings.Name = property.PropertyName;
                        settings.Properties.NullText = property.Watermark;
                        settings.Width = 200;
                        settings.Properties.ValidationSettings.RequiredField.IsRequired = property.IsRequired;
                        settings.ShowModelErrors = true;
                    }).Bind(ViewData[property.PropertyName]).GetHtml()
            </span>
        </div>
    }
</div>

那么表单会根据元数据很好地布局,标签、工具提示、水印等都从模型的元数据中提取出来; 但是,我希望能够将这些项目分组在一起,例如在每个组的

中。有谁知道如何从元数据中获取 GroupName,而不需要为 ModelMetadata 编写扩展方法?

The DisplayAttribute in System.ComponentModel.DataAnnotations has a GroupName property, which allows you to logically group fields together in a UI control (e.g. a property grid in WPF/WinForms).

I am trying to access this metadata in an ASP.NET MVC3 application, essentially to create a property grid. If my model looks like this:

public class Customer
{
    [ReadOnly]
    public int Id { get;set; }

    [Display(Name = "Name", Description = "Customer's name", GroupName = "Basic")]
    [Required(ErrorMessage = "Please enter the customer's name")]
    [StringLength(255)]
    public string Name { get;set; }

    [Display(Name = "Email", Description = "Customer's primary email address", GroupName = "Basic")]
    [Required]
    [StringLength(255)]
    [DataType(DataType.Email)]
    public string EmailAddress { get;set; }

    [Display(Name = "Last Order", Description = "The date when the customer last placed an order", GroupName = "Status")]
    public DateTime LastOrderPlaced { get;set; }

    [Display(Name = "Locked", Description = "Whether the customer account is locked", GroupName = "Status")]
    public bool IsLocked { get;set; }
}

and my view looks like this:

@model Customer

<div class="edit-customer">
    @foreach (var property in ViewData.ModelMetadata.Properties.Where(p => !p.IsReadOnly).OrderBy(p => p.Order))
    {
        <div class="editor-row">
            @Html.DevExpress().Label(settings =>
                {
                    settings.AssociatedControlName = property.PropertyName;
                    settings.Text = property.DisplayName;
                    settings.ToolTip = property.Description;
                }).GetHtml()
            <span class="editor-field">
                @Html.DevExpress().TextBox(settings =>
                    {
                        settings.Name = property.PropertyName;
                        settings.Properties.NullText = property.Watermark;
                        settings.Width = 200;
                        settings.Properties.ValidationSettings.RequiredField.IsRequired = property.IsRequired;
                        settings.ShowModelErrors = true;
                    }).Bind(ViewData[property.PropertyName]).GetHtml()
            </span>
        </div>
    }
</div>

then the form is laid out very nicely based on the metadata, with labels, tooltips, watermarks etc all pulled out of the model's metadata; but, I would like to be able to group the items together, for instance in a <fieldset> per group. Does anyone know how to get the GroupName out of the metadata, short of writing an extension method for ModelMetadata?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

最舍不得你 2025-01-15 00:54:31

GroupName 不由 DataAnnotationsModelMetadataProvider 解析。因此,即使使用扩展方法,也无法直接从 ModelMetadata 对象中获取它。

您可以实现自己的提供程序,扩展现有提供程序以添加对 GroupName 的支持,Brad Wilson 在他的博客中进行了解释

您还可以编写自己的属性,而不是使用 Display(GroupName = ) 并实现 IMetadataAware 接口,以将组名称添加到 ModelMetadata.AdditionalValues

GroupName is not parsed by the DataAnnotationsModelMetadataProvider. So there's no way to get it right off the ModelMetadata object, even with an extension method.

You could implement your own provider that extends the existing one to add support for GroupName, which Brad Wilson explains in his blog.

You could also write your own attribute instead of using Display(GroupName = ) and implement the IMetadataAware interface to add the groupname to ModelMetadata.AdditionalValues.

趴在窗边数星星i 2025-01-15 00:54:31

您还可以使用此扩展方法:

public static class ModelMetadataExtensions
{
  public static T GetPropertyAttribute<T>(this ModelMetadata instance)
    where T : Attribute
  {
    var result = instance.ContainerType
      .GetProperty(instance.PropertyName)
      .GetCustomAttributes(typeof(T), false)
      .Select(a => a as T)
      .FirstOrDefault(a => a != null);

    return result;
  } 
}

然后

var display= this.ViewData.ModelMetadata
  .GetPropertyAttribute<DisplayAttribute>();

var groupName = display.Groupname;

You can also use this Extension Method:

public static class ModelMetadataExtensions
{
  public static T GetPropertyAttribute<T>(this ModelMetadata instance)
    where T : Attribute
  {
    var result = instance.ContainerType
      .GetProperty(instance.PropertyName)
      .GetCustomAttributes(typeof(T), false)
      .Select(a => a as T)
      .FirstOrDefault(a => a != null);

    return result;
  } 
}

Then

var display= this.ViewData.ModelMetadata
  .GetPropertyAttribute<DisplayAttribute>();

var groupName = display.Groupname;
负佳期 2025-01-15 00:54:31

另一种方法是使用 ShortName< DisplayAttribute 类的 /code>属性。它ModelMetadata类公开为ShortDisplayName 属性。

这并不完全是您想要的,但它可以让您避免创建另一个属性类...最重要的是,您可以利用 DisplayAttribute 的本地化能力。

An alternative could be to use the ShortName property of the DisplayAttribute class. It is exposed by the ModelMetadata class as the ShortDisplayName property.

This isn't exactly what you're looking for, but it will allow you to avoid creating another attribute class...and on top of that, you can take advantage of the localization ability of the DisplayAttribute.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文