views:

23

answers:

1

Summary:

If you use ASP.NET MVC 2's templates to render a DropDownList, how would you access the list of options if they are stored in the top level View's Model.property? Also, is there some [DataAnnotation] way to associate this list? Links to examples would be very helpful.

Background:

In ASP.NET MVC 2, you can create a custom class like StateName and use an EditorTemplate called StateName.ascx, which will display that partial view anytime it finds a StateName property. Brad Wilson has a great write-up here describing it. These partial view templates can be nested so that each template only deals with it's own scope (matching the template's scope to the matching POCO's properties).

Setup:

Now imagine that the StateName.ascx renders a DropDownList and needs the list of possible states ([{"AL","Alabama"},{"PA","Pennsylvania"},...]). Generally, the top level View Model has all we need to render both the DomainModel (like our ShoppingCart), and any miscellaneous data like lists for drop downs.

Question:

So, the question is how does a partial view template StateName.ascx reference the non-partial top level view's Model property IList<StateName> States to populate the DDL in the partial view template? (especially if you have several nested or deep dive renderings like Model.Customer[0].BillingAddress.State, the template's parent view may not be the top level view).

Another angle may be to put some sort of [Data Annotation] on the class property that associates this list of possible states to the partial view template's Model?

For example, here's the top level View's Model:

Model.ShoppingCart.Customer.ShippingAddress;
Model.ShoppingCart.Customer.BillingAddress;
Model.StateNames;         // IList<StateName>
Model.MaritalStatusNames; // IList<MaritalStatus>
Model.GenderNames;        // IList<Gender>

Furthermore we could make all DDL data lists in one property, like Model.DDLs.StateNames, Model.DDLs.GenderNames, etc.?

+1  A: 

I think the short answer is that the partial template cannot access the parent's entire Model because it only receives the sub-model that it's meant to work with.

In your case (i.e. global lists of things that don't change) you could always declare your list in a static property on some helper object so that you don't need a model instance to be able to access it. For example your Address object could have a static list of all states.

marcind