views:

30

answers:

1

I have a simple model class (UserAddress) that is not being passed properly to the HttpPost function. The data always has null values for all the member data.

public class User
{
    public string Name { get; set; }
}

public class Address
{
    public string Address1;
    public string Address2;
}

public class UserAddress
{
    public User User;
    public Address Address;

    public UserAddress()
    {
        User = new User();
        Address = new Address();
    }
}

And a simple view:

<table>
    <tr>
        <td>
            <%: Html.LabelFor(model => model.User.Name) %>
        </td>
        <td>
            <%: Html.TextBoxFor(model => model.User.Name) %>
            <%: Html.ValidationMessageFor(model => model.User.Name) %>
        </td>
    </tr>
    <tr>
        <td>
            <%: Html.LabelFor(model => model.Address.Address1)%>
        </td>
        <td>
            <%: Html.TextBoxFor(model => model.Address.Address1)%>
            <%: Html.ValidationMessageFor(model => model.Address.Address1)%>
        </td>
    </tr>
    <tr>
        <td>
            <%: Html.LabelFor(model => model.Address.Address2)%>
        </td>
        <td>
            <%: Html.TextBoxFor(model => model.Address.Address2)%>
            <%: Html.ValidationMessageFor(model => model.Address.Address2)%>
        </td>
    </tr>
</table>

And here's the code:

 public ActionResult Index()
    {
        UserAddress userAddress = new UserAddress();

        return View(userAddress);
    }

    [HttpPost]
    public ActionResult Index(UserAddress userAddress)
    {
        return View(userAddress);
    }

All the member variables are null; such as userAddress.User.Name.

A: 

The only thing that stands out for me is that you are attempting to bind public members, not properties.

Perhaps try refactoring your classes to use properties and try that.

public class Address
{
    public string Address1 { get; set; }
    public string Address2 { get; set; }
}

public class UserAddress
{
    public User User { get; set; }
    public Address Address { get; set; }

    public UserAddress()
    {
        User = new User();
        Address = new Address();
    }
}
Phil Brown
i was about to post that answer, but thought it was too obvious. surely...
RPM1984
I tried that but the inner classes. But hadn't tried that for the UserAddress class. Duhhhh.
Dan Vallejo