MVC2 HttpPost未接收数据成员

时间:2010-10-29 04:25:25

标签: c# asp.net-mvc-2

我有一个简单的模型类(UserAddress)没有正确传递给HttpPost函数。数据始终具有所有成员数据的空值。

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

一个简单的观点:

<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>

这是代码:

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

        return View(userAddress);
    }

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

所有成员变量都为null;例如userAddress.User.Name。

1 个答案:

答案 0 :(得分:1)

对我来说唯一突出的是你试图绑定公共成员,而不是属性。

也许尝试重构您的类以使用属性并尝试。

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