自定义数据注释ASP.NET MVC C#

前端之家收集整理的这篇文章主要介绍了自定义数据注释ASP.NET MVC C#前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有关于MVC 2与C#的以下问题.

这是我的型号:

public class Pmjob
{
   [Tooltext="Hier soll der Name eingegeben werden"]
   [DisplayName("Type")]
   public int Name { get; set; }
}

现在我想在我的视图中找到Tooltext项,e. G.:

@Html.ToolTextFor(Model => Model.Pmjob.Name)

或在BL:

if ( Model.Pmjob.Name.Tooltext == "") {
}

这可能吗?

解决方法

创建一个抽象类MetaDataAttribute:
public abstract class MetadataAttribute : Attribute
{
    /// <summary>
    /// Method for processing custom attribute data.
    /// </summary>
    /// <param name="modelMetaData">A ModelMetaData instance.</param>
    public abstract void Process(ModelMetadata modelMetaData);
}

使您的属性继承自MetaDataAttribute:

public class ToolTextAttribute : MetadataAttribute
{
    public string Text { get; set; }
    public TooltextAttribute(string text)
    {
        this.Text = new text;
    }

    public override void Process(ModelMetadata modelMetaData)
    {
        modelMetaData.AdditionalValues.Add("ToolText",this.Text);
    }
}

创建自定义MetaDataProvider:

public class CustomModelMetadataProvider : DataAnnotationsModelMetadataProvider
{
    protected override ModelMetadata CreateMetadata(
        IEnumerable<Attribute> attributes,Type containerType,Func<object> modelAccessor,Type modelType,string propertyName)
    {
        var modelMetadata = base.CreateMetadata(attributes,containerType,modelAccessor,modelType,propertyName);
        attributes.OfType<MetadataAttribute>().ToList().ForEach(x => x.Process(modelMetadata));
        return modelMetadata;
    }
}

并替换默认的(global.asax.cs):

protected void Application_Start()
{
    // snipped

    ModelMetadataProviders.Current = new CustomModelMetadataProvider();
}

最后,您可以在视图(或Html Helper)中访问它:

(string)ViewData.ModelMetadata.AdditionalValues.Where(x => x.Key == "ToolText").SingleOrDefault()

资源 :

> http://weblogs.asp.net/seanmcalinden/archive/2010/06/11/custom-asp-net-mvc-2-modelmetadataprovider-for-using-custom-view-model-attributes.aspx
> http://weblogs.asp.net/seanmcalinden/archive/2010/06/12/asp-net-mvc-2-auto-complete-textbox-custom-view-model-attribute-amp-editortemplate.aspx

猜你在找的asp.Net相关文章