ntombela
ntombela

Reputation: 1388

Passing model data to asp.net mvc EditorTemplates

ScottGu in this post link text shows how one can utilize EditorTemplates for things such as a Country DropDownList. My question is how can one pass a dynamic list of Countries to the EditorTemplate?

Upvotes: 0

Views: 1770

Answers (4)

jm.
jm.

Reputation: 23714

Similar to @Benja's answer

You can also use the [AdditionaMetaData(key,value)] attribute in a similar fashion without having to define your own attribute. Key and value have to be strings.

The extra data can be retrieved in the view with: @ViewData.ModelMetadata.AdditionalValues["DropDownData"]

Upvotes: 0

Benja
Benja

Reputation: 4154

Probably the most elegant solution is using a Custom Attribute, you can later access Model metadata using: ViewData.ModelMetadata.

e.g:

 [Foreign(Type="DropDown", TableName="Countries")]
   public int IdCountry { get; set; }

where ForeignAttribute is a class you must declare, and later use it to build your editor template.

Upvotes: 1

Michael Brown
Michael Brown

Reputation: 9143

Even better you make the partial view strongly typed and pass the model to the EditorFor helper

@Html.EditorFor(m=>m.SelectedCountry, Model.AvailableCountries)

Upvotes: 1

mtmk
mtmk

Reputation: 6316

You can pass it in ViewData and feed ViewData from and ActionFilter if the data is required very often (although arguable it is an anti-pattern).

Upvotes: 0

Related Questions