本文介绍了自定义数据注解ASP.NET MVC C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我对MVC 2与C#的follwing问题。
I have the follwing question about MVC 2 with C#.
下面是我的模型:
public class Pmjob
{
[Tooltext="Hier soll der Name eingegeben werden"]
[DisplayName("Type")]
public int Name { get; set; }
}
现在我想在我看来,电子到达Tooltext项目。 G:
Now I want to reach the Tooltext item in my view, e. g.:
@Html.ToolTextFor(Model => Model.Pmjob.Name)
或在BL:
if ( Model.Pmjob.Name.Tooltext == "") {
}
这可能吗?
推荐答案
创建一个抽象类MetaDataAttribute:
Create an abstract class 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:
Make your attribute inherit from 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:
Create the custom 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):
And replace the default one (global.asax.cs) :
protected void Application_Start()
{
// snipped
ModelMetadataProviders.Current = new CustomModelMetadataProvider();
}
最后,您可以在您的视图访问(或在HTML辅助):
Finally, you can access it in your view (or in a Html Helper ) :
(string)ViewData.ModelMetadata.AdditionalValues.Where(x => x.Key == "ToolText").SingleOrDefault()
来源:
这篇关于自定义数据注解ASP.NET MVC C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!