【问题标题】:KnownType attribute on a property during model binding in MVC?在 MVC 中的模型绑定期间属性上的 KnownType 属性?
【发布时间】:2011-09-28 17:23:33
【问题描述】:

假设我有一个类 Food 和一个派生自 Food 的 BirdFood 类:

public class Food
{
   ...
}

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

假设我有一个类 Creature 和一个派生自 Creature 的类 Bird

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

public class Bird : Creature
{
   ...
}

最后,假设我有一个 Creature 的视图模型:

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

当我创建 Bird 的实例时,我还创建了 BirdFood 的实例并将其分配给 Food 属性并将视图模型传递给 View。很简单。

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

        viewModel.Creature = new Bird();

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

        return View(viewModel);
    }

还有观点:

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

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

   <input type="submit" />

<% } %>

好的,问题来了。当在 Action 中接收到视图模型时,Creature 属性是基类 Creature 而不是派生类型 Bird 具有派生类型 BirdFood 的 SeedCount 属性,其后参数(来自 firebug)看起来像Creature.Food.SeedCount 100

好的,我的问题是,如何在模型绑定时保留派生类型?我怀疑它与自定义模型绑定器有关,但我对此一无所知。有什么想法吗?

【问题讨论】:

    标签: c# asp.net asp.net-mvc asp.net-mvc-3 c#-4.0


    【解决方案1】:

    默认模型绑定器只是检查视图模型中的类型并使用这些类。他猜不出你想要一些派生类。 custom model binder 可用于提供此类提示。这是another one

    【讨论】:

    • 摇滚乐。希望有一个简单且更原生的解决方案,但这将完成工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-16
    • 2014-07-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多