默认 ModelBinder 无法正常工作
我有以下结构:
public class Dummy
{
public string Name { get; set; }
public InnerDummy Dum { get; set; }
}
public class InnerDummy
{
public string Name { get; set; }
}
和一个接收 Dummy
的 ActionResult
[HttpPost]
public ActionResult Index(Dummy dum)
{
var dsad = dum;
//var dwss = idum;
return RedirectToAction("index");
}
在我看来,我有:
@model TestMVC3Razor.Controllers.HomeController.Dummy
@using (Html.BeginForm())
{
@Html.TextBoxFor(o => o.Name)
@Html.EditorFor(o => o.Dum)
<br />
<br />
<input type="submit" />
}
它正在发布
Name=xxx
Dum.Name=yyy
但是当我尝试获取 dum.Dum.Name 时
在 ActionResult
上,我得到 null
而不是 yyy
。这是一个错误还是就是这样?是不是我用的不对?我需要为此实现一个新的活页夹吗?
I have this following structure:
public class Dummy
{
public string Name { get; set; }
public InnerDummy Dum { get; set; }
}
public class InnerDummy
{
public string Name { get; set; }
}
And an ActionResult
that receives a Dummy
[HttpPost]
public ActionResult Index(Dummy dum)
{
var dsad = dum;
//var dwss = idum;
return RedirectToAction("index");
}
On my view I have:
@model TestMVC3Razor.Controllers.HomeController.Dummy
@using (Html.BeginForm())
{
@Html.TextBoxFor(o => o.Name)
@Html.EditorFor(o => o.Dum)
<br />
<br />
<input type="submit" />
}
It is posting
Name=xxx
Dum.Name=yyy
But when I try to get dum.Dum.Name
on the ActionResult
I get null
instead of yyy
. Is this a bug or just the way it is? Am I not using it right? Do I need to implement a new binder for this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你好~你的视图应该使用
@Html.EditorFor(o => o.Dum.Name)
而不是
@Html.EditorFor(o => o.Dum)
并且回发控制器:
如果您有任何问题,请告诉我:)
HI~ your view should use
@Html.EditorFor(o => o.Dum.Name)
not
@Html.EditorFor(o => o.Dum)
And postback Controller:
If you have problems about it, please let me know :)
您需要从
Dummy
类中取出InnerDummy
。当默认模型绑定器找到
Dum
属性时,它将尝试创建InnerDummy
类型的对象,但在其上下文中并不存在。要引用InnerDummy
,模型绑定器需要创建一个Dummy.InnerDummy
,但它无法知道这一点。让
InnerDummy
成为命名空间的直接成员将解决该问题。也可以通过将
Dum
声明为来解决该问题:不过,我对此不确定。
You need to pull the
InnerDummy
out from inside theDummy
class.When the default model binder finds the
Dum
property it will try to create an object of typeInnerDummy
, but in its context that doesn't exist. To referenceInnerDummy
as you have it the model binder would need to create aDummy.InnerDummy
, but it has no way of knowing that.Making
InnerDummy
a direct member of the namespace will fix the problem.It may also be possible to fix the problem by declaring
Dum
as:I'm not sure about this, though.