How to bind a property value of a nested array element with a TextBox in ASP.NET MVC

I have a 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 the user addresses to be displayed as a list. I do it on the watch 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 the data in the text field filled in for the operator is empty. Of course, I can add the following TextBox method to assign the value, but the two text fields up (for example, "user.Name") read / set the value correctly.

What am I doing wrong?

PS. I am using MVC RTM 1.0

+3
source share
2 answers

The Html.TextBox method requires 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>

Html.TextBoxFor MVC Futures

+1

texbox "name" "id", value .

:

<% =Html.TextBox("user.Addresses[" + index + "].Street", user.Addresses[index].Street)%>        
0

Source: https://habr.com/ru/post/1705323/


All Articles