views:

496

answers:

2

Does anyone have an example of buddy classes in ASP.NET MVC 2 Preview 1? I can't seem to find anything on the MSDN about it but according to ScottGu they've added functionality for it in the most recent release.

+3  A: 

Scott Gu tweeted about it this morning, here is the link

Jason w
Excellent, thank you.
Nathan Taylor
+7  A: 

I believe what you're looking for is MetadataTypeAttribute. This isn't something that's specific to MVC but it part of the DataAnnotations namespace introduced in 3.5. It allows you to decorate members of a partial class external to the class itself.

For instance, if you had a generated partial class type named Customer and wanted to add attributes to it, you could create a new partial in the same namespace and tag it with the MetadataType. Then create the Metadata class with matching attributes and decorate them.

/* Generated class */
public partial class Customer
{ 
  public string Name { get; set; } 
}


/* MetadataType decorated class */
[MetadataType(CustomerMetadata)]
public partial class Customer
{ /* ... */ }


/* Metadata type */
public class CustomerMetadata
{
  [Required(ErrorMessage = "Name is required")]
  public string Name { get; set; }
}
andymeadows
Thanks tons! That's exactly what I needed. :)
Nathan Taylor
What's the point in seperating the classes?
UpTheCreek
It's not so much a "point" as it is an ugly workaround to handling auto-generated classes from EF or LINQ2SQL. Because the class files are generated there's no way to apply attributes to the properties, thus a hacky alternative was created.
Nathan Taylor
I'm trying to use this approach, but the only attribute that seems to work in EditorForModel() is 'DisplayName'.
ProfK