微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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编写扩展方法

解决方法

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

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

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐