0

I wrote a custom binder, but i can't seem to get it running. Here's my code:

 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 };
        }           
    }
}

I added this to my global.asax.cs:

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

but when i try to run this:

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

... }

i still get a System.MissingMethodException saying: cannot create abstract class

Where am i going wrong?

Sincerely,

Zoli

Zoltan Varadi
  • 2,468
  • 2
  • 34
  • 51

1 Answers1

0

Check this link.you might find the solution here: ASP.NET MVC 2 - Binding To Abstract Model

The answer has a custom model binder.

Community
  • 1
  • 1
TRR
  • 1,637
  • 2
  • 26
  • 43