title: Model binding with dynamic form controls
body: <p>I'm looking to store arithmetic expressions to a database. I have this db structure:</p>
  
  <pre><code>Expression
  =======
  id
  name
  
  Operand
  =======
  id
  expressionId
  value
  side (indicates if the operand is on the left or right side of the expression)
  idx (the index to identify the order of operands on each side)
  
  Operator
  ========
  id
  expressionId
  type
  side
  idx
  </code></pre>
  
  <p>In my View, I want to provide the user the ability to create an expression with a variable number of operands and operators by adding controls dynamically to the page upon request. If the user clicks the "Add operand" button, a dropdown will be generated for the operator via javascript, and a textbox will be generated for the operand.</p>
  
  <p>My thought is to use custom model binding in my expression's Create action and work with a viewmodel:</p>
  
  <pre><code>public class ExpressionCreateViewModel
  {
  IEnumerable&lt;ExpressionOperator&gt; Operators { get; set; }
  IEnumerable&lt;ExpressionOperand&gt; Operands { get; set; }
  Expression Expression { get; set; }
  }
  </code></pre>
  
  <p>The model binder would work with it:</p>
  
  <pre><code>public class ExpressionCreateViewModelBinder : IModelBinder
  {
      public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
      {
          var vm = new ExpressionCreateViewModel();
          //Build it!
      }
  </code></pre>
  
  <p>What I'm leery of is how I would have to pass in the dynamically generated control's values into this view model. The only way I can think of doing it is creating control IDs that provide all the details (e.g. &lt;input type="text" id="operand:1$side:left"&gt;)</p>
  
  <p>Then I could parse through the items in the form collection and by convention build the operand and operator objects.</p>
  
  <p>Does anyone have a cleaner way to do this?</p>
  
  <p>Thanks!</p>
  
  <p>Chris</p>