DefaultModelBinder不绑定嵌套模型

hac*_*sid 12 asp.net-mvc viewmodel asp.net-mvc-2

看起来其他人有这个问题,但我似乎无法找到解决方案.

我有2个型号:Person&BillingInfo:

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

public class BillingInfo
{
 public string BillingName { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我正在尝试使用DefaultModelBinder将此直接绑定到我的Action中.

public ActionResult DoStuff(Person model)
{
 // do stuff
}
Run Code Online (Sandbox Code Playgroud)

但是,在设置Person.Name属性时,BillingInfo始终为null.

我的帖子看起来像这样:

"NAME = statichippo&BillingInfo.BillingName = statichippo"

为什么BillingInfo总是为空?

Vic*_*ber 9

我有这个问题,答案就是盯着我看了几个小时.我在这里包括它,因为我正在寻找没有绑定的嵌套模型,并得出了这个答案.

确保嵌套模型的属性(如您希望绑定适用的任何模型)具有正确的访问者.

    // Will not bind!
    public string Address1;
    public string Address2;
    public string Address3;
    public string Address4;
    public string Address5;


    // Will bind
    public string Address1 { get; set; }
    public string Address2 { get; set; }
    public string Address3 { get; set; }
    public string Address4 { get; set; }
    public string Address5 { get; set; }
Run Code Online (Sandbox Code Playgroud)


Dar*_*rov 6

状态无重复.您的问题在其他地方,无法确定您从哪里获取信息.默认模型绑定器与嵌套类完美匹配.我已经无限次地使用它并且它一直有效.

模型:

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

public class BillingInfo
{
    public string BillingName { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

控制器:

[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);
    }
}
Run Code Online (Sandbox Code Playgroud)

视图:

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

发布值:Name=statichippo&BillingInfo.BillingName=statichippo完全绑定在POST操作中.同样适用于GET.


这可能不起作用的一种可能情况如下:

public ActionResult Index(Person billingInfo)
{
    return View();
}
Run Code Online (Sandbox Code Playgroud)

请注意如何调用action参数billingInfo,与BillingInfo属性的名称相同.确保这不是你的情况.