加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – DefaultModelBinder不绑定嵌套模型

发布时间:2020-12-16 00:18:02 所属栏目:asp.Net 来源:网络整理
导读:看起来其他人有这个问题,但我似乎无法找到解决方案. 我有2个型号:人物计费信息: public class Person{ public string Name { get; set;} public BillingInfo BillingInfo { get; set; }}public class BillingInfo{ public string BillingName { get; set;
看起来其他人有这个问题,但我似乎无法找到解决方案.

我有2个型号:人物&计费信息:

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

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

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

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

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

我的帖子看起来像这样:

“Name=statichippo&BillingInfo.BillingName=statichippo”

为什么BillingInfo总是为空?

解决方法

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

模型:

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

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

控制器:

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

视图:

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

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

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

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读