{"id":16119,"date":"2015-02-16T12:00:51","date_gmt":"2015-02-16T11:00:51","guid":{"rendered":"http:\/\/infozone.se\/?p=16119"},"modified":"2015-02-16T12:00:51","modified_gmt":"2015-02-16T11:00:51","slug":"binding-abstract-models-asp-net-mvc","status":"publish","type":"post","link":"https:\/\/www.infozone.se\/en\/latest-news\/binding-abstract-models-asp-net-mvc\/","title":{"rendered":"Binding abstract models in ASP.NET MVC"},"content":{"rendered":"<p>Having trouble binding abstract models in ASP.NET MVC? Hopefully this will help.<\/p>\n<h2>The problem<\/h2>\n<p>It is common to have abstract models but it can be a bit of struggle to make it work together with MVC\u2019s built in model binder. I guess a lot of people have faced the following yellow screen of death (\u201cCannot create an abstract class\u201d):<\/p>\n<p><img decoding=\"async\" class=\"alignnone size-full wp-image-23451\" src=\"\/wp-content\/uploads\/2017\/05\/RL2_YellowScreenOfDeath.jpg\" alt=\"\" width=\"675\" height=\"167\" \/><\/p>\n<p>A lot of approaches for this particular issue flourish the web. Such as:<\/p>\n<ul>\n<li>For JSON data, using the <a title=\"TypeNameHandling\" href=\"http:\/\/www.newtonsoft.com\/json\/help\/html\/T_Newtonsoft_Json_TypeNameHandling.htm\" target=\"_blank\" rel=\"noopener noreferrer\">TypeNameHandling <\/a>setting to include the .NET fully qualified name of the model<\/li>\n<li>One action per concrete model and then let the client route to the specific action<\/li>\n<li>A hidden field in the form that describes the .NET fully qualified name of the model<\/li>\n<li>Etc.<\/li>\n<\/ul>\n<p>These approaches feels a bit hacky and cumbersome to me, whereas I\u2019ve created an alternative approach.<\/p>\n<h2>An alternative approach<\/h2>\n<p>I often tend to include an enum type to my abstract classes that defines the underlying concrete type. Something similar to:<\/p>\n<p><img decoding=\"async\" class=\"alignnone size-full wp-image-23452\" src=\"\/wp-content\/uploads\/2015\/02\/RL2_ModelDomain.png\" alt=\"\" width=\"619\" height=\"396\" \/><\/p>\n<p>Since the model\u2019s type is present as a value, why not opt-in and guide the DefaultModelBinder what the concrete type of the model is (based on the enum type value provided in the request) and then let the binder continue do its magic.<\/p>\n<pre class=\"EnlighterJSRAW\">public class CustomModelBinder&lt;TEnum&gt; : DefaultModelBinder\n    where TEnum : struct\n{\n    private readonly string _key;\n    private readonly Dictionary&lt;TEnum, Type&gt; _typeMapper;\n\n    public CustomModelBinder(string key, Dictionary&lt;TEnum, Type&gt; typeMapper)\n    {\n        _key = key;\n        _typeMapper = typeMapper;\n    }\n\n    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)\n    {\n        ValueProviderResult value = bindingContext.ValueProvider.GetValue(_key);\n\n        TEnum @enum;\n        if (value == null || !Enum.TryParse(value.AttemptedValue, true, out @enum)\n            || !_typeMapper.ContainsKey(@enum))\n        {\n            return base.BindModel(controllerContext, bindingContext);\n        }\n\n        bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, _typeMapper[@enum]);\n        return base.BindModel(controllerContext, bindingContext);\n    }\n}<\/pre>\n<p>The CustomModelBinder hooks into the binding process by overrid\u00edng the BindModel method of the DefaultModelBinder. The custom binder updates the binding context\u2019s metadata with the concrete type, based on the type value in the request, and then the DefaultModelBinder continue its work.<\/p>\n<p>The ConcreteModelBinderAttribute is created to decorate in-parameters and serves the purpose to instantiate the correct model binder. One attribute should be created per abstract model.<\/p>\n<pre class=\"EnlighterJSRAW\">public class ConcreteModelBinderAttribute : CustomModelBinderAttribute\n{\n    private readonly string _key;\n\n    public ConcreteModelBinderAttribute(string key = \"type\")\n    {\n        _key = key;\n    }\n\n    public override IModelBinder GetBinder()\n    {\n        return new CustomModelBinder(_key, new Dictionary&lt;ConcreteType, Type&gt;\n        {\n            {ConcreteType.A, typeof (ConcreteA)},\n            {ConcreteType.B, typeof (ConcreteB)}\n        });\n    }\n}<\/pre>\n<p>&nbsp;<\/p>\n<p>For the sake of this example, I just added a dictionary that serves as a type map but one could change this to use an IoC-container,  ServiceLocator, or similar instead.<\/p>\n<h2>Example<\/h2>\n<p>So if we create an MVC controller as follows (the in-parameter is decorated with the ConcreteModelBinder described previously):<\/p>\n<pre class=\"EnlighterJSRAW\">public class ExampleController : Controller\n{\n    [HttpPost]\n    public ActionResult Index([ConcreteModelBinder]Base model)\n    {\n        return Json(model);\n    }\n}<\/pre>\n<p>And use the marvellous chrome extension Postman to create a POST request to the server. We get the following result:<\/p>\n<p><img decoding=\"async\" class=\"alignnone size-medium wp-image-23312\" src=\"\/wp-content\/uploads\/2015\/02\/RL2_ResultA-300x238.jpg\" alt=\"\" width=\"300\" height=\"238\" \/><\/p>\n<p><img decoding=\"async\" class=\"alignnone size-medium wp-image-23314\" src=\"\/wp-content\/uploads\/2015\/02\/RL2_ResultA-1-300x238.jpg\" alt=\"\" width=\"300\" height=\"238\" \/><\/p>\n<p>The model binder now instantiate the correct concrete class, the only thing we have to remember is to provide the type in the request to the server.<\/p>\n<p>Great success.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>It is common to have abstract models but it can be a bit of struggle to make it work together with MVC\u2019s built in model binder. I guess a lot of people have faced the following yellow screen of death (\u201cCannot create an abstract class\u201d)<\/p>\n","protected":false},"author":2,"featured_media":21360,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[118],"tags":[120,121],"class_list":["post-16119","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-blog","tag-asp-net-sv","tag-mvc-sv"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v24.4 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Binding abstract models in ASP.NET MVC - Infozone - English<\/title>\n<meta name=\"description\" content=\"Binding abstract models in ASP.NET MVC - It is common to have abstract models but it can be a struggle to make it work with MVC\u2019s built in model binder.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.infozone.se\/en\/latest-news\/binding-abstract-models-asp-net-mvc\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Binding abstract models in ASP.NET MVC - Infozone - English\" \/>\n<meta property=\"og:description\" content=\"Binding abstract models in ASP.NET MVC - It is common to have abstract models but it can be a struggle to make it work with MVC\u2019s built in model binder.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.infozone.se\/en\/latest-news\/binding-abstract-models-asp-net-mvc\/\" \/>\n<meta property=\"og:site_name\" content=\"Infozone - English\" \/>\n<meta property=\"article:published_time\" content=\"2015-02-16T11:00:51+00:00\" \/>\n<meta name=\"author\" content=\"Eva-Katrine\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Eva-Katrine\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"3 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"WebPage\",\"@id\":\"https:\/\/www.infozone.se\/en\/latest-news\/binding-abstract-models-asp-net-mvc\/\",\"url\":\"https:\/\/www.infozone.se\/en\/latest-news\/binding-abstract-models-asp-net-mvc\/\",\"name\":\"Binding abstract models in ASP.NET MVC - Infozone - English\",\"isPartOf\":{\"@id\":\"https:\/\/www.infozone.se\/en\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/www.infozone.se\/en\/latest-news\/binding-abstract-models-asp-net-mvc\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/www.infozone.se\/en\/latest-news\/binding-abstract-models-asp-net-mvc\/#primaryimage\"},\"thumbnailUrl\":\"\",\"datePublished\":\"2015-02-16T11:00:51+00:00\",\"author\":{\"@id\":\"https:\/\/www.infozone.se\/en\/#\/schema\/person\/0d207ef1167f0800247368907c22564a\"},\"description\":\"Binding abstract models in ASP.NET MVC - It is common to have abstract models but it can be a struggle to make it work with MVC\u2019s built in model binder.\",\"breadcrumb\":{\"@id\":\"https:\/\/www.infozone.se\/en\/latest-news\/binding-abstract-models-asp-net-mvc\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/www.infozone.se\/en\/latest-news\/binding-abstract-models-asp-net-mvc\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/www.infozone.se\/en\/latest-news\/binding-abstract-models-asp-net-mvc\/#primaryimage\",\"url\":\"\",\"contentUrl\":\"\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/www.infozone.se\/en\/latest-news\/binding-abstract-models-asp-net-mvc\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Hem\",\"item\":\"https:\/\/www.infozone.se\/en\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Binding abstract models in ASP.NET MVC\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/www.infozone.se\/en\/#website\",\"url\":\"https:\/\/www.infozone.se\/en\/\",\"name\":\"Infozone - English\",\"description\":\"We Create Heroes\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/www.infozone.se\/en\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Person\",\"@id\":\"https:\/\/www.infozone.se\/en\/#\/schema\/person\/0d207ef1167f0800247368907c22564a\",\"name\":\"Eva-Katrine\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/www.infozone.se\/en\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/a9dd68bbfbf1db963362df5ee0d60cae5806a7b43ce6eea550eb059f74c95eb9?s=96&d=mm&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/a9dd68bbfbf1db963362df5ee0d60cae5806a7b43ce6eea550eb059f74c95eb9?s=96&d=mm&r=g\",\"caption\":\"Eva-Katrine\"},\"url\":\"https:\/\/www.infozone.se\/en\/latest-news\/author\/eva-katrine\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Binding abstract models in ASP.NET MVC - Infozone - English","description":"Binding abstract models in ASP.NET MVC - It is common to have abstract models but it can be a struggle to make it work with MVC\u2019s built in model binder.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.infozone.se\/en\/latest-news\/binding-abstract-models-asp-net-mvc\/","og_locale":"en_US","og_type":"article","og_title":"Binding abstract models in ASP.NET MVC - Infozone - English","og_description":"Binding abstract models in ASP.NET MVC - It is common to have abstract models but it can be a struggle to make it work with MVC\u2019s built in model binder.","og_url":"https:\/\/www.infozone.se\/en\/latest-news\/binding-abstract-models-asp-net-mvc\/","og_site_name":"Infozone - English","article_published_time":"2015-02-16T11:00:51+00:00","author":"Eva-Katrine","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Eva-Katrine","Est. reading time":"3 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"WebPage","@id":"https:\/\/www.infozone.se\/en\/latest-news\/binding-abstract-models-asp-net-mvc\/","url":"https:\/\/www.infozone.se\/en\/latest-news\/binding-abstract-models-asp-net-mvc\/","name":"Binding abstract models in ASP.NET MVC - Infozone - English","isPartOf":{"@id":"https:\/\/www.infozone.se\/en\/#website"},"primaryImageOfPage":{"@id":"https:\/\/www.infozone.se\/en\/latest-news\/binding-abstract-models-asp-net-mvc\/#primaryimage"},"image":{"@id":"https:\/\/www.infozone.se\/en\/latest-news\/binding-abstract-models-asp-net-mvc\/#primaryimage"},"thumbnailUrl":"","datePublished":"2015-02-16T11:00:51+00:00","author":{"@id":"https:\/\/www.infozone.se\/en\/#\/schema\/person\/0d207ef1167f0800247368907c22564a"},"description":"Binding abstract models in ASP.NET MVC - It is common to have abstract models but it can be a struggle to make it work with MVC\u2019s built in model binder.","breadcrumb":{"@id":"https:\/\/www.infozone.se\/en\/latest-news\/binding-abstract-models-asp-net-mvc\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.infozone.se\/en\/latest-news\/binding-abstract-models-asp-net-mvc\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.infozone.se\/en\/latest-news\/binding-abstract-models-asp-net-mvc\/#primaryimage","url":"","contentUrl":""},{"@type":"BreadcrumbList","@id":"https:\/\/www.infozone.se\/en\/latest-news\/binding-abstract-models-asp-net-mvc\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Hem","item":"https:\/\/www.infozone.se\/en\/"},{"@type":"ListItem","position":2,"name":"Binding abstract models in ASP.NET MVC"}]},{"@type":"WebSite","@id":"https:\/\/www.infozone.se\/en\/#website","url":"https:\/\/www.infozone.se\/en\/","name":"Infozone - English","description":"We Create Heroes","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.infozone.se\/en\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Person","@id":"https:\/\/www.infozone.se\/en\/#\/schema\/person\/0d207ef1167f0800247368907c22564a","name":"Eva-Katrine","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.infozone.se\/en\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/a9dd68bbfbf1db963362df5ee0d60cae5806a7b43ce6eea550eb059f74c95eb9?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/a9dd68bbfbf1db963362df5ee0d60cae5806a7b43ce6eea550eb059f74c95eb9?s=96&d=mm&r=g","caption":"Eva-Katrine"},"url":"https:\/\/www.infozone.se\/en\/latest-news\/author\/eva-katrine\/"}]}},"acf":[],"_links":{"self":[{"href":"https:\/\/www.infozone.se\/en\/wp-json\/wp\/v2\/posts\/16119","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.infozone.se\/en\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.infozone.se\/en\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.infozone.se\/en\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/www.infozone.se\/en\/wp-json\/wp\/v2\/comments?post=16119"}],"version-history":[{"count":0,"href":"https:\/\/www.infozone.se\/en\/wp-json\/wp\/v2\/posts\/16119\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.infozone.se\/en\/wp-json\/wp\/v2\/media?parent=16119"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.infozone.se\/en\/wp-json\/wp\/v2\/categories?post=16119"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.infozone.se\/en\/wp-json\/wp\/v2\/tags?post=16119"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}