0
public abstract class AbstractSearch
{
    public string Property { get; set; }
    public string TargetTypeName { get; set; }
}

public class DateSearch : AbstractSearch
{
    public DateTime? SearchTerm { get; set; }
    public DateComparators Comparator { get; set; }
}

public enum DateComparators
{
    Less,
    LessOrEqual,
    Equal,
    GreaterOrEqual,
    Greater,
    InRange
}

public class SearchViewModel
{
    public IEnumerable<AbstractSearch> SearchCriteria { get; set; }
}

How to pass above properties to SearchViewModel class from clientside JSON.

I need to pass Property, TargetTypeName, SearchTerm, Comparator from javascript to webapi through Json.

Iam using Web api 2.0 as Serverside. Is it possible to pass Json parameter into Inherited class?

Pradees
  • 191
  • 1
  • 4
  • 17
  • 4
    Possible duplicate of [Deserializing JSON to abstract class](http://stackoverflow.com/questions/20995865/deserializing-json-to-abstract-class) – aloisdg Mar 16 '17 at 14:39
  • why not ```public IEnumerable SearchCriteria { get; set; }```? – tym32167 Mar 16 '17 at 14:40
  • is it possible without SearchViewModel class? – Pradees Mar 16 '17 at 14:41
  • @tym32167 I'm assuming OP has other classes that inherit from the abstract, thus needing to reference the abstract and not the concrete implementation – maccettura Mar 16 '17 at 14:41

1 Answers1

1

If you specify the concrete type when serializing on the client-side you can make this work using TypeNameHandling. You specify the type using a $type property in the JSON.

The model-binder won't be able to instantiate an abstract-class.

Configure JSON.NET:

GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.TypeNameHandling = TypeNameHandling.Auto;

Then post your JSON in this format:

{
    "$type": "Namespace.DateSearch, AssemblyName"
    "Property": "..."
    "etc": ""
}
Robert Massa
  • 4,345
  • 1
  • 32
  • 44