Search code examples
c#asp.net-mvc-3modelbinders

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 />
    <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?


Solution

  • 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 :)