2

I'm using ASP.NET MVC RC1 and trying to bind a textbox to an object property like so:

<%= Html.TextBox("Comments.Contacts[0].ContactName") %>

It seems like it should work, since this does:

<%= ((MuralProject)ViewData.Model).Comments.Contacts[0].ContactName %>

But alas, the result in the textbox is an empty string. Am I doing something wrong?

1 Answer 1

3

The first argument for the text box extension method sets the name of the input element that's eventually created and also tries to get an entry from ViewData/Model (for the model it uses TypeDescriptors / reflection) based on that argument.

The way it does this is just by splitting up the input string at the dots then checking the ViewDataDictionary for specific keys and the Model via reflection so in the case you give it'll try and look for Contacts[0] rather than Contacts and won't pick up your property.

To get around this you just need to supply the actual value of the object e.g.

Html.TextBox("Comments.Contacts[0].ContactName", 
             Model.Comments.Contacts[0].ContactName)

You can see this yourself if you look at the MVC source and take a peek at the ViewDataDictionary class.

Sign up to request clarification or add additional context in comments.

2 Comments

Interesting. Without the array it seems to work with a single parameter. Thanks.
Updated as to why it doesn't work with arrays, basically it's trying to find a property with the name Contacts[0] rather than Contacts and giving up

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.