Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><strong>Update:</strong> Example now uses a AJAX JSON POST</p> <p>If you must use an abstract type, you could provide a <a href="http://msdn.microsoft.com/en-us/library/system.web.mvc.imodelbinder.aspx" rel="noreferrer">custom model binder</a> to create the concrete instance. An example is shown below:</p> <p><strong>Model / Model Binder</strong></p> <pre><code>public abstract class Student { public abstract int Age { get; set; } public abstract string Name { get; set; } } public class GoodStudent : Student { public override int Age { get; set; } public override string Name { get; set; } } public class BadStudent : Student { public override int Age { get; set; } public override string Name { get; set; } } public class StudentBinder : IModelBinder { public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { var values = (ValueProviderCollection) bindingContext.ValueProvider; var age = (int) values.GetValue("Age").ConvertTo(typeof (int)); var name = (string) values.GetValue("Name").ConvertTo(typeof(string)); return age &gt; 10 ? (Student) new GoodStudent { Age = age, Name = name } : new BadStudent { Age = age, Name = name }; } } </code></pre> <p><strong>Controller Actions</strong></p> <pre><code>public ActionResult Index() { return View(new GoodStudent { Age = 13, Name = "John Smith" }); } [HttpPost] public ActionResult Index(Student student) { return View(student); } </code></pre> <p><strong>View</strong></p> <pre><code>@model AbstractTest.Models.Student @using (Html.BeginForm()) { &lt;div id="StudentEditor"&gt; &lt;p&gt;Age @Html.TextBoxFor(m =&gt; m.Age)&lt;/p&gt; &lt;p&gt;Name @Html.TextBoxFor(m =&gt; m.Name)&lt;/p&gt; &lt;p&gt;&lt;input type="button" value="Save" id="Save" /&gt;&lt;/p&gt; &lt;/div&gt; } &lt;script type="text/javascript"&gt; $('document').ready(function () { $('input#Save').click(function () { $.ajax({ url: '@Ajax.JavaScriptStringEncode(Url.Action("Index"))', type: 'POST', data: GetStudentJsonData($('div#StudentEditor')), contentType: 'application/json; charset=utf-8', success: function (data, status, jqxhr) { window.location.href = '@Url.Action("Index")'; } }); }); }); var GetStudentJsonData = function ($container) { return JSON.stringify({ 'Age': $container.find('input#Age').attr('value'), 'Name': $container.find('input#Name').attr('value') }); }; &lt;/script&gt; </code></pre> <p><strong>Added to Global.asax.cs</strong></p> <pre><code>protected void Application_Start() { ... ModelBinders.Binders.Add(new KeyValuePair&lt;Type, IModelBinder&gt;(typeof(Student), new StudentBinder())); } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload