asp .net mvc自定义模型绑定失败

时间:2012-04-25 12:28:11

标签: asp.net-mvc

我写了一个自定义活页夹,但我似乎无法让它运行。 这是我的代码:

 public abstract class SlideItem
{
   public string PlaceHolderName { get; set; }
    public uint PlaceHolderID { get; set; }
    public uint ItemType { get; set; }
}

public class TitleSlideItem : SlideItem
    {
       ...

        public TitleSlideItem()
        {
            ItemType = 1;
        }
    }



public class ParagraphSlideItem : SlideItem
{
     ...
     public ParagraphSlideItem()
    {
        ItemType = 2;
    }
}

 public class SlideItemBinder : IModelBinder

{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {

        System.Diagnostics.Trace.WriteLine("BindModel is working");

        var values = (ValueProviderCollection)bindingContext.ValueProvider;
        var placeHolderName = (string)values.GetValue("PlaceHolderName").ConvertTo(typeof(string));
        var placeHolderID = (uint)values.GetValue("PlaceHolderID").ConvertTo(typeof(uint));
        var itemType = (uint)values.GetValue("ItemType").ConvertTo(typeof(uint));
        switch (itemType)
        {
            case 1:
                System.Diagnostics.Trace.WriteLine("TitleSlideItemBinder");
                return (SlideItem)new TitleSlideItem { PlaceHolderName = placeHolderName };
            case 2:
                System.Diagnostics.Trace.WriteLine("ParagraphSlideItem");
                return (SlideItem)new ParagraphSlideItem { PlaceHolderName = placeHolderName };
            case 3:
                System.Diagnostics.Trace.WriteLine("TextSlideItem");
                return (SlideItem)new TextSlideItem { PlaceHolderName = placeHolderName };
            case 4:
                System.Diagnostics.Trace.WriteLine("PictureSlideItem");
                return (SlideItem)new PictureSlideItem { PlaceHolderName = placeHolderName };
            default:
                System.Diagnostics.Trace.WriteLine("this should never-ever-ever-ever happen");
                //this should never-ever-ever-ever happen
                return (SlideItem)new TextSlideItem { PlaceHolderName = placeHolderName };
        }           
    }
}

我将此添加到我的global.asax.cs:

     ModelBinders.Binders.Add(new KeyValuePair<Type, IModelBinder>(typeof(SlideItem), new SlideItemBinder()));           

但是当我尝试运行时:

 [System.Web.Http.HttpPost]
 public HttpResponseMessage Create(IList<SlideContent> l)
        {

...     }

我仍然得到一个System.MissingMethodException:无法创建抽象类

我哪里错了?

此致

佐利

1 个答案:

答案 0 :(得分:0)

检查此链接。您可以在此处找到解决方案:ASP.NET MVC 2 - Binding To Abstract Model

答案有一个自定义模型绑定器。