Ant
no notes

Global Level Resource Declaration

Ok, the last blog on Model Level Resource Declaration allows you to set the resource at a model level, but what if your models are not in your UI layer and your resources are?

How about registering the type of resource to use for a particular model type, model type hierarchy or even globally, for example ...

protected void Application_Start() {
    AreaRegistration.RegisterAllAreas();

    RegisterGlobalFilters(GlobalFilters.Filters);
    RegisterRoutes(RouteTable.Routes);

    DependencyResolver.SetResolver(
        t => {
            if (t == typeof (ModelMetadataProvider)) {
                return new DisplayResourceMetadataProvider();
            }
            return null;
        },
        t => { return new object[] {}; });

    // Use the following resource for all types
    DisplayResourceMetadataProvider
        .UseForProperty<GlobalResource>();

    // Use the following resource for Person and Derived
    DisplayResourceMetadataProvider
        .UseForProperty<PersonResource>(typeof(PersonModel));

}

The DisplayResourceMetadataProvider overrides the ModelMetadata.DisplayName which is then shown when using Html.LabelFor in your view.

To demonstrate the hierarchical retrieval there are two types in the application

public class PersonInfoModel {
    public string Name { get; set; }
    public string Email { get; set; }
    public string MobileNumber { get; set; }
}

public class PersonModel : PersonInfoModel {
    public string Biography { get; set; }
}

With the following Resources

Running the attached application you are presented with a link to two forms..

With the code as above, where PersonResource is assigned to PersonModel, the Person Info form will not find any resources in PersonResource and will fall back to those found in GlobalResource..

If you change the registration to use PersonInfoModel instead of PersonModel..

// Use the following resource for Person and Derived
DisplayResourceMetadataProvider
    .UseForProperty<PersonResource>(typeof(PersonInfoModel));

then the form will render with resources found in PersonResource.. fab

Attached

Sandbox.DisplayResources.zip ASP.NET MVC 3 VS2010 solution

Post a Note

(required)

(required never shown)

On Twitter Follow MrAntix on Twitter

15/05/2012
WindowsAzure
Announcing the MEET Windows Azure Event! Streamed online June 7th. Register at http://t.co/bObzTAuL  #MEETAzure #WindowsAzure

10/05/2012
kevinwhinnery
Comparing Titanium and PhoneGap - A common question I get asked at developer events and conferences is how... http://t.co/Zq2eND6B

09/05/2012
brianleroux
PhoneGap goals and philosophy: http://t.co/wkq8wI2T

just now
mstechfeed
#MSDN Virtual Lab: #Windows Azure: Running a Parametric Sweep Applications with the Windows Azure HPC Scheduler http://t.co/3676GXSQ

just now
ilcomm
#android #jobs encrypting phonegap android by joseesfera http://t.co/s4VgtPhs #israel #iphone