57

I have a custom editor template where I add values to the ViewData like so:

@Html.EditorFor( model => model.PhoneNumber , new { Title = "SomeValue" } )

How can I access both the value and the property name?

dav_i
  • 27,509
  • 17
  • 104
  • 136
Boo
  • 1,634
  • 3
  • 20
  • 29
  • See my example here: http://stackoverflow.com/a/9400359/1173800 – jhilden Feb 22 '12 at 18:04
  • 1
    In case someone else has the same problem as me and appears here from Google - I could not understand why my ViewData["Something"] was null in my custom EditorFor. It turned out that I was loading a different view in my browser from the one where I added the anonymous type to test it out. Silly mistake. – DavGarcia Nov 15 '12 at 00:20

2 Answers2

63

ViewData is a dictionary.

You can write ViewData["Title"], or you can loop through ViewData (which is a collection of KeyValuePairs) or ViewData.Keys.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
34

You can nest your htmlAttributes object in view data:

<%= Html.EditorFor(model => model.PhoneNumber, new { htmlAttributes = new { Title = "SomeValue" } })

Then in your editor template:

<%= Html.TextBox("", Model.Value, ViewData["htmlAttributes"])%>
FRj
  • 341
  • 3
  • 2