首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >DefaultModelBinder非绑定嵌套模型

DefaultModelBinder非绑定嵌套模型
EN

Stack Overflow用户
提问于 2010-10-13 21:20:31
回答 5查看 13.7K关注 0票数 14

看来其他人也有这个问题,但我似乎找不到解决办法。

我有两个模特: Person & BillingInfo:

代码语言:javascript
复制
public class Person
{
 public string Name { get; set;}
 public BillingInfo BillingInfo { get; set; }
}

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

我正试图用DefaultModelBinder将其直接绑定到我的Action中。

代码语言:javascript
复制
public ActionResult DoStuff(Person model)
{
 // do stuff
}

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

我的帖子是这样的:

"Name=statichippo&BillingInfo.BillingName=statichippo“

为什么BillingInfo总是空的?

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2010-10-13 21:27:41

状态没有复制。你的问题在其他地方,无法从你提供的信息中确定你的位置。默认的模型绑定器在嵌套类中非常好地工作。我已经用了无数次了,而且它一直在起作用。

型号:

代码语言:javascript
复制
public class Person
{
    public string Name { get; set; }
    public BillingInfo BillingInfo { get; set; }
}

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

主计长:

代码语言:javascript
复制
[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);
    }
}

查看:

代码语言:javascript
复制
<% using (Html.BeginForm()) { %>
    Name: <%: Html.EditorFor(x => x.Name) %>
    <br/>
    BillingName: <%: Html.EditorFor(x => x.BillingInfo.BillingName) %>
    <input type="submit" value="OK" />
<% } %>

POST值:Name=statichippo&BillingInfo.BillingName=statichippo完全绑定在POST操作中。GET也同样有效。

一种可能的情况是这样做不起作用:

代码语言:javascript
复制
public ActionResult Index(Person billingInfo)
{
    return View();
}

请注意动作参数是如何调用billingInfo的,与BillingInfo属性的名称相同。确保这不是你的案子。

票数 6
EN

Stack Overflow用户

发布于 2015-05-29 14:22:07

我遇到了这个问题,这个问题的答案一直盯着我几个小时。我把它包括在这里,因为我在寻找嵌套模型,而不是绑定,并得出了这个答案。

确保嵌套模型的属性(就像希望绑定工作的任何模型一样)具有正确的访问器。

代码语言:javascript
复制
    // 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; }
票数 14
EN

Stack Overflow用户

发布于 2017-01-25 09:24:20

我也有同样的问题,项目的前一位开发人员在一个私人设置器上注册了这个属性,因为他在回发中没有使用这个视图模型。就像这样:

代码语言:javascript
复制
public MyViewModel NestedModel { get; private set; }

改为:

代码语言:javascript
复制
public MyViewModel NestedModel { get; set; }
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3928120

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档