DefaultModelBinder 不绑定嵌套模型
看起来其他人也遇到过这个问题,但我似乎找不到解决方案。
我有 2 个模型:人和BillingInfo:
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 总是为空?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我遇到了这个问题,答案就在我面前盯着我几个小时。我将其包含在这里是因为我正在搜索不绑定的嵌套模型并得出了这个答案。
确保嵌套模型的属性(与您希望绑定起作用的任何模型一样)具有正确的访问器。
I had this problem, and the answer was staring me in the face for a few hours. I'm including it here because I was searching for nested models not binding and came to this answer.
Make sure that your nested model's properties, like any of your models that you want the binding to work for, have the correct accessors.
状态无重现。您的问题在其他地方,无法从您提供的信息中确定出在哪里。默认模型绑定器与嵌套类完美配合。我已经使用它无数次了,而且一直有效。
模型:
控制器:
视图:
发布值:
Name=statichippo&BillingInfo.BillingName=statichippo
完美绑定在 POST 操作中。 GET 也同样适用。一种可能不起作用的情况如下:
请注意操作参数如何称为
billingInfo
,其名称与BillingInfo
属性相同。确保这不是您的情况。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:
Controller:
View:
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:
Notice how the action parameter is called
billingInfo
, same name as theBillingInfo
property. Make sure this is not your case.我遇到了同样的问题,该项目的前一位开发人员已使用私有设置器注册了该属性,因为他没有在回发中使用此视图模型。像这样的事情:
改成这样:
I had the same issue, the previous developer on the project had the property registered with a private setter as he wasn't using this viewmodel in a postback. Something like this:
changed to this:
这对我有用。
我将其更改
为:
This is what worked for me.
I changed this:
To:
我也遇到过类似的问题。我花了很多时间无意中发现了问题,我不应该使用“model”作为属性名称
I have had the similiar problem. I spent many hours and find the problem accidentally that I should not use 'model' for the property name