title: MVC3 Validate total for list of elements
body: <p>I have a View Model that represents a total bill and list of parties that are splitting the bill.  The parties splitting the bill each take a certain percentage of the total (example: Party A takes 50%, Party B takes 20%, Party C takes 30%).</p>
  
  <p>The model looks something like this:</p>
  
  <pre><code>public class BillModel
  {
      public int Total { get; set; }
      public List&lt;BillPartyModel&gt; Parties { get; set; }
  }
  
  public class BillPartyModel
  {
      public string Name { get; set; }
      public int SplitPercentage { get; set; }
  }
  </code></pre>
  
  <p>Basically, I want to validate that the <code>SplitPercentage</code> for all parties totals to exactly 100.  I was initially tempted to add custom validation attribute to <code>SplitPercentage</code>, but I'm not sure how to sum all the values in the validator.  Could I perhaps add a custom validation attribute to <code>Parties</code> in the main model (and how would that work)?  Or does someone know a better way to do this?</p>
  
  <p><strong>EDIT:</strong>
  I did as suggested below and ended up with this (using DataAnnotationsExtensions for the EqualTo tag):</p>
  
  <p><em>Model</em></p>
  
  <pre><code>[EqualTo("TotalPercent", ErrorMessage = "Percentages do not add up to 100%.")]
  public int SplitPercentage { get { return this.Allocations.Sum(a =&gt; a.Allocation); } }
  public int TotalPercent { get { return 100; } }
  </code></pre>
  
  <p><em>View</em></p>
  
  <pre><code>@Html.HiddenFor(m =&gt; m.SplitPercentage)
  @Html.ValidationMessageFor(m =&gt; m.SplitPercentage)
  @Html.EditorFor(m =&gt; m.BillPartyModel)
  </code></pre>
  
  <p>...And then I just use a JavaScript OnChange event to update the AllocationTotal in order to get Client-Side validation.</p>