2010-09-30 5 views
9

im Moment habe ich dies:erhalten Wert von benutzerdefinierten Attributs in Editor Vorlage

im Ansichtsmodell:

[MyCustom(Foo = 23)] 
public int CountryId { get; set; } 

im Editor-Vorlage:

<%= Html.TextBox("", Model) %> 

wie kann ich das bekommen Wert (Foo = 23) von meinem benutzerdefinierten Attribut (MyCustom) in die Editor-Vorlage?

+0

hier ein [Blog-Post] (http://weblogs.asp.net/seanmcalinden/archive/2010/06/12/asp-net-mvc-2-auto-complete-textbox-custom-view -model-attribute-amp-editorortplate.aspx), die Sie möglicherweise nützlich finden. –

Antwort

8

In Editor-Vorlage können Sie den Wert von benutzerdefinierten Attribut wie folgt abrufen.

@model int 

@{  
    var CustomAttributes = (ViewData.ModelMetadata).ContainerType.GetProperty(ViewData.ModelMetadata.PropertyName).GetCustomAttributes(typeof(MvcApplication7.Models.MyCustomAttribute), false); 
    if (CustomAttributes.Length > 0) 
    { 
     MvcApplication7.Models.MyCustomAttribute CustomAttribute = CustomAttributes[0] as MvcApplication7.Models.MyCustomAttribute; 

     //That is how you get the value of foo. You can use it as per need of the editor template. 
     @CustomAttribute.Foo 
    } 
}