Dav*_*eny 5 data-annotations asp.net-mvc-3
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; }
}
Run Code Online (Sandbox Code Playgroud)
我的观点看起来像这样:
@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>
Run Code Online (Sandbox Code Playgroud)
然后根据元数据很好地布置表单,标签,工具提示,水印等都从模型的元数据中拉出; 但是,我希望能够将这些项目组合在一起,例如在<fieldset>每个组中.有没有人知道如何从元数据中获取GroupName,而不是为ModelMetadata编写扩展方法?
GroupName没有被解析DataAnnotationsModelMetadataProvider.因此ModelMetadata,即使使用扩展方法,也无法将其从对象上移除.
您可以实现自己的提供程序,扩展现有的提供程序以添加对GroupName的支持,Brad Wilson 在其博客中解释了这一点.
您也可以编写自己的属性,而不是使用Display(GroupName = )和实现IMetadataAware接口来添加组名ModelMetadata.AdditionalValues.
| 归档时间: |
|
| 查看次数: |
2107 次 |
| 最近记录: |