ASP.NET MVC ModelMetaData:有没有办法基础上,以RequiredAttribute标签设置IsRequired? [英] ASP.NET MVC ModelMetaData: Is there a way to set IsRequired based on the RequiredAttribute?

查看:139
本文介绍了ASP.NET MVC ModelMetaData:有没有办法基础上,以RequiredAttribute标签设置IsRequired?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

布拉德·威尔逊张贴在ASP.NET MVC的新ModelMetaData一个伟大的博客系列:
<一href=\"http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-2-modelmetadata.html\">http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-2-modelmetadata.html

Brad Wilson posted a great blog series on ASP.NET MVC's new ModelMetaData: http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-2-modelmetadata.html

在书中,他描述了如何ModelMetaData类的观点和模板助手,现在暴露出来。我想要做的是显示一个表单字段标签旁边的星号,如果需要的领域,所以我想过使用ModelMetaData的IsRequired财产。然而,IsRequired默认情况下是所有非空的性能真的,而这对所有可能为空的属性假的。问题是,字符串总是为空的,所以IsRequired属性始终字符串假。有谁知道如何重写的IsRequired是如何设置的默认?另外,我想到了充分利用,我一直在与装饰我的属性属性RequiredAttribute标签,但似乎RequiredAttribute标签不通过ModelMetaData类被曝光。有谁知道如何解决这个问题?

In it, he describes how the ModelMetaData class is now exposed in the Views and templated helpers. What I'd like to do is display an asterisk beside a form field label if the field is required, so I thought about using the IsRequired property of ModelMetaData. However, IsRequired by default is true for all non-nullable properties, while it's false for all nullable properties. The problem is, strings are always nullable, so the IsRequired property is always false for strings. Does anyone know how to override the default of how IsRequired is set? Alternatively, I thought about leveraging the RequiredAttribute attribute that I've been decorating my properties with, but the RequiredAttribute doesn't seem to be exposed through the ModelMetaData class. Does anyone know how to get around this problem?

先谢谢了。

推荐答案

您需要创建自己的ModelMetadataProvider。下面是一个使用DataAnnotationsModelBinder一个例子

You need to create your own ModelMetadataProvider. Here's an example using the DataAnnotationsModelBinder

public class MyMetadataProvider : DataAnnotationsModelMetadataProvider
{
        protected override ModelMetadata CreateMetadata(Collections.Generic.IEnumerable<Attribute> attributes, Type containerType, Func<object> modelAccessor, Type modelType, string propertyName)
        {
            var _default = base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName);
            _default.IsRequired = attributes.Where(x => x is RequiredAttribute).Count() > 0;
            return _default;
        }
}

然后在Global.asax中的AppStartup,你会希望把下面来装MyMetadataProvider为默认的元数据提供程序:

Then in your AppStartup in Global.asax, you will want to put the following in to hookup the MyMetadataProvider as the default metadata provider:

ModelMetadataProviders.Current = new MyMetadataProvider();

这篇关于ASP.NET MVC ModelMetaData:有没有办法基础上,以RequiredAttribute标签设置IsRequired?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆