MVC UpdateModel ComplexType

时间:2009-03-13 14:23:47

标签: asp.net-mvc updatemodel

如果您有以下类型。

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public List<TheParameters> Parameters { get; set; }
    public Address Address { get; set; }
}
public class Address
{
    public string Street { get; set; }
    public string City { get; set; }
    public string State { get; set; }
}
public class TheParameters
{
    public string Parameter { get; set; }
}

您将页面强制设置为Person。

"System.Web.Mvc.ViewPage<Person>"

<form action="/Home/Save" method="post">  

    <b>Your Name</b> 
    <label for="FirstName">  
        <span>First Name</span>  
        <%=Html.TextBox("Person.FirstName", ViewData.Model.FirstName) %>  
    </label>  

    <label for="LastName">  
        <span>Last Name</span>  
        <%=Html.TextBox("Person.LastName", ViewData.Model.LastName)%>  
    </label>  

    <b>Your Address</b>  

    <label for="Street">  
        <span>Street</span>  
        <%=Html.TextBox("Person.Address.Street", ViewData.Model.Address.Street)%>  
    </label>  

    <label for="City">  
        <span>City</span>  
        <%=Html.TextBox("Person.Address.City", ViewData.Model.Address.City)%>  
    </label>  

    <label for="State">  
        <span>State</span>  
        <%=Html.TextBox("Person.Address.State", ViewData.Model.Address.State)%>  
    </label>  

    <label for="Parameters">
        <span>Parameters</span>
        <%
            int index = 0;
            foreach (TheParameters parameter in ViewData.Model.Parameters)
            {
                Response.Write(Html.TextBox("Person.Parameters.Parameter[" + index + "]", parameter.Parameter));
                index++;
            }
         %>
    </label>

    <input id="submit" type="submit" value="submit" />  

</form> 

在控制器中有以下内容:

    public ActionResult Index()
    {
        Person p = new Person();
        p.FirstName = "Name";
        p.LastName = "Last";
        p.Address = new Address();
        p.Address.City = "city";
        p.Address.State = "state";
        p.Address.Street = "street";

        p.Parameters = new List<TheParameters>();
        p.Parameters.Add(new TheParameters(){ Parameter = "P1" });
        p.Parameters.Add(new TheParameters(){ Parameter = "p2" });

        ViewData.Model = p;

        return View();
    }

    public ActionResult Save(FormCollection form)   
    {
        Person p = new Person();


        UpdateModel(p, "Person", form.ToValueProvider());

        return RedirectToAction("Index");

    }

我调用UpdateModel。除Person.Parameters外,所有属性都已正确填充。在updateModel之后,它始终为null。

是否有解决方案或解决方法?

的问候, 史蒂夫

1 个答案:

答案 0 :(得分:0)

在您看来:

"Person.Parameters.Parameter[" + index + "]" 

应该是

"Person.Parameters[" + index + "].Parameter"