tags:

views:

24

answers:

2

I have the folowing code in my view, however, I can see that I don`t have the values in the controller. What is wrong? In the view I have,

<%
    using (Html.BeginForm())
    {%>
       <%=Html.TextBox("Addresses[0].Line1") %>
       <%=Html.TextBox("Addresses[0].Line2")%>
       <%=Html.TextBox("Addresses[1].Line1")%>
       <%=Html.TextBox("Addresses[1].Line2")%>

        <input type="submit" name="submitForm" value="Save products" />
        <%
    }
%>

My classes are as follows:

public class Customer
{
    public string FirstName { get; set; }
    public string Lastname { get; set; }
    public List<Address> Addresses { get; set; }
    public Customer()
    {
        Addresses = new List<Address>();
    }
}

public class Address
{
    public int Line1 { get; set; }
    public int Line2 { get; set; }
}

My controller as follows:

public ActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Index(Customer customer)
    {
        return View();
    }
A: 

The parameter for your ActionResult is named customer, so the default model binder will be looking for that name in the form by default. I believe if you modify your code to the following it should pick it up:

   <%=Html.TextBox("customer.Addresses[0].Line1") %>
   <%=Html.TextBox("customer.Addresses[0].Line2")%>
   <%=Html.TextBox("customer.Addresses[1].Line1")%>
   <%=Html.TextBox("customer.Addresses[1].Line2")%>
dtrickett
A: 

Check to ensure your View is bound to the Customer model.

Also, when viewing the web page containing the form, view the source generated by the View to see if the fields are being properly named.

Finally, if none of the above helps, change the parameter in your Index action like so:

public ActionResult Index(FormCollection form)

then you can use the debugger to inspect the FormCollection object that is passed in to see exactly what the View is sending you.

Mike Pollitt
with form I can see that the data are sent to the controller. I don`t want to use the formcollection as the textboxes are dynamically created and removed. Isn`t there any other way of doing it?
the values will be dynamically created, formcollection doesn`t remain the best option in this case I suppose?