开发者

KnownType attribute on a property during model binding in MVC?

Lets say I have the class Food and a class BirdFood that derives from Food:

public class Food
{
   ...
}

public class BirdFood : Food
{
    public int SeedCount { get; set; }
}

And lets say I have a class Creature and a class Bird 开发者_如何学编程that derives from Creature

public class Creature
{
    public Food Food { get; set; }
}

public class Bird : Creature
{
   ...
}

And finally, lets say I have a view model for Creature:

public class ViewModel
{
    public Creature Creature { get; set; }
}

When I create an instance of Bird, I also create an instance of BirdFood and assign it to the Food property and pass the view model to the View. Simple enough.

    public ActionResult Index()
    {
        ViewModel viewModel = new ViewModel();

        viewModel.Creature = new Bird();

        viewModel.Creature.Food = new BirdFood() { SeedCount = 100 } ;

        return View(viewModel);
    }

And the view:

<% using(Html.BeginForm("Save", "Home", FormMethod.Post))
   { %>

   <%: Html.Hidden("Creature.Food.SeedCount", (Model.Creature.Food as MvcApplication6.Controllers.BirdFood).SeedCount)  %>

   <input type="submit" />

<% } %>

Okay, here is the problem. When the view model is received in the Action, the Creature property is of the base class Creature instead of the derived type Bird with the SeedCount property of the derived type BirdFood with the post parameters (from firebug) that looks like Creature.Food.SeedCount 100

KnownType attribute on a property during model binding in MVC?

Okay, my questions is, how do I preserve the derived types when model binded? I'm suspecting it has to do with a custom Model Binder but I'm clueless when it comes to that. Any ideas?


The default model binder simply inspects the types in your view model and uses those classes. He cannot guess that you want some derived class. A custom model binder could be used to provide such hint. And here's another one.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜