views:

34

answers:

1

Looks like others have had this problem but I can't seem to find a solution.

I have 2 Models: Person & BillingInfo:

public class Person
{
 public string Name { get; set;}
 public BillingInfo BillingInfo { get; set; }
}

public class BillingInfo
{
 public string BillingName { get; set; }
}

And I'm trying to bind this straight into my Action using the DefaultModelBinder.

public ActionResult DoStuff(Person model)
{
 // do stuff
}

However, while the Person.Name property is set, the BillingInfo is always null.

My post looks like this:

"Name=statichippo&BillingInfo.BillingName=statichippo"

Why is BillingInfo always null?

+2  A: 

Status no repro. Your problem is elsewhere and unable to determine where from what you've given as information. The default model binder works perfectly fine with nested classes. I've used it an infinity of times and it has always worked.

Model:

public class Person
{
    public string Name { get; set; }
    public BillingInfo BillingInfo { get; set; }
}

public class BillingInfo
{
    public string BillingName { get; set; }
}

Controller:

[HandleError]
public class HomeController : Controller
{
    public ActionResult Index()
    {
        var model = new Person
        {
            Name = "statichippo",
            BillingInfo = new BillingInfo
            {
                BillingName = "statichippo"
            }
        };
        return View(model);
    }

    [HttpPost]
    public ActionResult Index(Person model)
    {
        return View(model);
    }
}

View:

<% using (Html.BeginForm()) { %>
    Name: <%: Html.EditorFor(x => x.Name) %>
    <br/>
    BillingName: <%: Html.EditorFor(x => x.BillingInfo.BillingName) %>
    <input type="submit" value="OK" />
<% } %>

Posted values: Name=statichippo&BillingInfo.BillingName=statichippo is perfectly bound in the POST action. Same works with GET as well.


One possible case when this might not work is the following:

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

Notice how the action parameter is called billingInfo, same name as the BillingInfo property. Make sure this is not your case.

Darin Dimitrov
You're right. Turns out my HTML had an issue and was outputting:
statichippo
statichippo