views:

1096

answers:

2

Hi,

I have model

public class User 
{
    public User()
    {
       Addreses = new List<Address>();
    }
    public String Name { get; set; }
    public String LastName { get; set; }
    public List<Address> Addresses { get; private set; }
}

public class Address
{
    public String Street { get; set; }
    public String City { get; set; }
}

And I want do display user addresses as ul list. I do this in view page

    using (Html.BeginForm("UpdateUser", "Home", FormMethod.Post))
    {
%>
<% =Html.TextBox("user.Name")%><br />
<% =Html.TextBox("user.LastName")%><br />
<ul>
    <% 
       for (Int32 index = 0; index < ((User)ViewData["user"]).Addresses.Count; index++)
       {%>
    <li>
        <% =Html.TextBox("user.Addresses[" + index + "].Street")%>,
        <% =Html.TextBox("user.Addresses[" + index + "].PostalCode")%>,
        <% =Html.TextBox("user.Addresses[" + index + "].City")%>
    </li>
    <% 
       }
    %>
</ul>
<input type="submit" value="Submit" />
<% }%>

And data in textboxes populated in for statement are empty. Ofcourse I could add next parameter TextBox method to assign value, but two textboxes upper (for instance "user.Name") correctly read/set value.

What I'm doing wrong?

PS. I'm using MVC RTM 1.0

A: 

In your example you are only setting the texbox's "name" and "id" attributes and not the value object as the second overload.

try this:

<% =Html.TextBox("user.Addresses[" + index + "].Street", user.Addresses[index].Street)%>
Mark
Yes, but <% =Html.TextBox("user.Name") %> correctly read value from ViewData. And I don't know why doing the same with lists require manually setting value.
zielu1
+1  A: 

The Html.TextBox method need the name of the control and the value of the control

<ul>
    <%foreach (var address in ((User)ViewData["user"]).Addresses){ 
        <li>
            <% =Html.TextBox("Street", address.Street)%>,
            <% =Html.TextBox("PostalCode", address.PostalCode)%>,
            <% =Html.TextBox("City", address.City)%>
        </li>
    <%}%>
</ul>

you can also try using the Html.TextBoxFor method in the MVC Futures project

Rony