dvallejo
dvallejo

Reputation: 1053

MVC2 HttpPost Not Receiving Data Members

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.

Upvotes: 1

Views: 606

Answers (1)

Phil
Phil

Reputation: 164924

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();
    }
}

Upvotes: 1

Related Questions