title: ASP.NET MVC 1.0 - Model binder for Dictionaries
body: <p>I have a <em>ViewModel</em> class containing a Dictionary (and other irrelevant things for this question):</p>
  
  <pre><code>public class MyViewModel {
      public Dictionary&lt;int, string&gt; Data { get; set; }
      /* ... */
  }
  </code></pre>
  
  <p>Then I have a couple of <code>GET</code>/<code>POST</code> actions that deal with the dictionary. The <code>GET</code> action will first fill the <code>Dictionary&lt;int, string&gt;</code> with some data from the database, and then return a <code>View</code>:</p>
  
  <ul>
  <li>the <code>.Key</code>s will be on <em>hidden fields</em>; and</li>
  <li>the <code>.Value</code>s will be on a <em>textareas</em> for the user to edit.</li>
  </ul>
  
  <p>The user will then submit this form, calling the <code>POST</code> action. It will try to process the input (the process is irrelevant). Some of the <code>Key</code>/<code>Value</code> pairs will be <strong>valid</strong>, some will be <strong>invalid</strong>.</p>
  
  <p>If there are invalid pairs, the <code>POST</code> action will then reconstruct a <em>ViewModel</em>, but this time the dictionary should contain only the <strong>invalid</strong> pairs, and will redisplay the same View for the user to fix and try submitting again.</p>
  
  <p><strong>Question:</strong> what is the easiest &amp; cleanest way to achieve this?</p>
  
  <p>What I have so far (working fine), in the controller:</p>
  
  <pre><code>public ActionResult MyAction(MyViewModel vm) {
      /* Process data */
      if (are there invalid pairs?) {
          var vmErrors = new MyViewModel();
          /* ... fill the ViewModel ... */
          vmErrors.Data = 
              vm.Data
                  .Where(x =&gt; IsInvalid(x))
                  .ToDictionary(x =&gt; x.Key, x =&gt; x.Value);
          return View(vmErrors);
      }
  }
  </code></pre>
  
  <p>And the view:</p>
  
  <pre><code>&lt;% var i = 0; foreach (var p in Model.Data) { %&gt;
      &lt;%= Html.Hidden("vm.Data[" + i + "].key", vm.Key %&gt;
      &lt;%= Html.TextArea("vm.Data[" + i + "].value", vm.Value %&gt;
  &lt;% i++; } %&gt;
  </code></pre>
  
  <p>The problem is that to please the <em>model binder</em> I must name my fields on the view with sequential ids. But I must also iterate over the Dictionary to extract the key/value pairs, so it cannot be a <code>for (var i = 0; i &lt; Model.Data.Count; i++) {...}</code> loop.</p>