Note that there are some explanatory texts on larger screens.

plurals
  1. POIssue With Custom Collection Model Binder in MVC 3
    primarykey
    data
    text
    <p>I'm having an issue creating a model binder in MVC.</p> <p>The action that I'm targeting looks like:</p> <pre><code>public ActionResult GetAccounts (ICollection&lt;Account&gt; accounts ){} </code></pre> <p>I created a custom model binder and registered it with the following code:</p> <pre><code>ModelBinders.Binders.Add(typeof(ICollection&lt;Account&gt;),new CollectionModelBinder()); </code></pre> <p>With a debugger attached, I can see that the <code>CollectionModelBinder's CreateModel</code> method is being called. However, when execution reaches the action method of the controller, the accounts parameter is null.</p> <p>What's the issue?</p> <p>My model binder looks like:</p> <pre><code>public class CollectionModelBinder : DefaultModelBinder { protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType) { return new List&lt;Account&gt; { new Account {Id = 1}, new Account {Id = 2}, new Account {Id = 3}}; } } </code></pre> <p><strong>UPDATE:</strong></p> <p>This was a problem with <code>DefaultModelBinder.</code> After <code>CreateModel</code> was called, another internal method, <code>UpdateCollection</code> was called, which effectively nulled out the collection that was created by <code>CreateModel.</code> The solution was to roll my own implementation of <code>IModelBinder.</code> The only argument that's missing on <code>IModelBinder.BindModel</code> is the <code>modelType,</code> which is easy to get:</p> <pre><code>public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { var type = bindingContext.ModelType; //... } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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