我有关于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); }
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); } }
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