MVC3 Validate total for list of elements
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%).
The model looks something like this:
public class BillModel
{
public int Total { get; set; }
开发者_C百科public List<BillPartyModel> Parties { get; set; }
}
public class BillPartyModel
{
public string Name { get; set; }
public int SplitPercentage { get; set; }
}
Basically, I want to validate that the SplitPercentage
for all parties totals to exactly 100. I was initially tempted to add custom validation attribute to SplitPercentage
, but I'm not sure how to sum all the values in the validator. Could I perhaps add a custom validation attribute to Parties
in the main model (and how would that work)? Or does someone know a better way to do this?
EDIT: I did as suggested below and ended up with this (using DataAnnotationsExtensions for the EqualTo tag):
Model
[EqualTo("TotalPercent", ErrorMessage = "Percentages do not add up to 100%.")]
public int SplitPercentage { get { return this.Allocations.Sum(a => a.Allocation); } }
public int TotalPercent { get { return 100; } }
View
@Html.HiddenFor(m => m.SplitPercentage)
@Html.ValidationMessageFor(m => m.SplitPercentage)
@Html.EditorFor(m => m.BillPartyModel)
...And then I just use a JavaScript OnChange event to update the AllocationTotal in order to get Client-Side validation.
public int Total { get { return Parties.Sum(p=>p.SplitPercentage); } }
Then when you are validating the model make sure Total = 100
You could look at using the custom validation attribute and create a editor template for your List<BillPartyModel>
see here for a demo
In your custom validation attribute you can then check the model easily and loop over the split percentage properties to see they total 100
精彩评论