Default ModelBinder not working properly
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 />开发者_如何学Python
<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?
HI~ your view should use @Html.EditorFor(o => o.Dum.Name)
not @Html.EditorFor(o => o.Dum)
And postback Controller:
[HttpPost]
public ActionResult Index(Dummy postback)
{
var dsad = postback;
var a = postback.Name; //get Name of Dummy
var b = postback.Dum.Name; //get Name of InnerDummy of Dummy
return RedirectToAction("index");
}
If you have problems about it, please let me know :)
You need to pull the InnerDummy
out from inside the Dummy
class.
When the default model binder finds the Dum
property it will try to create an object of type InnerDummy
, but in its context that doesn't exist. To reference InnerDummy
as you have it the model binder would need to create a Dummy.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:
public Dummy.InnerDummy Dum { get; set; }
I'm not sure about this, though.
精彩评论