gpt4 book ai didi

asp.net-mvc-3 - 如何从 ModelMetadata 检索 GroupName 数据注释

转载 作者:行者123 更新时间:2023-12-03 02:15:01 25 4
gpt4 key购买 nike

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>

然后,表单根据元数据很好地布局,标签、工具提示、水印等都从模型的元数据中提取出来; 但是,我希望能够将这些项目分组在一起,例如在 <fieldset> 中每组。有谁知道如何从元数据中获取 GroupName,而不需要为 ModelMetadata 编写扩展方法?

最佳答案

GroupName未被 DataAnnotationsModelMetadataProvider 解析。所以没有办法直接从 ModelMetadata 中获取它。对象,即使有扩展方法。

您可以实现自己的提供程序来扩展现有提供程序以添加对 GroupName 的支持,Brad Wilson explains in his blog .

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

关于asp.net-mvc-3 - 如何从 ModelMetadata 检索 GroupName 数据注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9387008/

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