You need to specify the helpers link;
using NerdDinner.Helpers;
and
using NerdDinner.Models;
Then check the correctness and add errors;
if (!dinner.IsValid) { ModelState.AddModelErrors(dinner.GetRuleViolations()); return View(dinner); }
You should also have a partial class for your dinner;
public partial class Dinner { public bool IsValid { get { return (GetRuleViolations().Count() == 0); } } public IEnumerable<RuleViolation> GetRuleViolations() { if (String.IsNullOrEmpty( SomeField )) yield return new RuleViolation("Field value text is required", "SomeField"); } partial void OnValidate(ChangeAction action) { if (!IsValid) throw new ApplicationException("Rule violations prevent saving"); } }
Do not forget the RuleViolation class;
public class RuleViolation { public string ErrorMessage { get; private set; } public string PropertyName { get; private set; } public RuleViolation(string errorMessage) { ErrorMessage = errorMessage; } public RuleViolation(string errorMessage, string propertyName) { ErrorMessage = errorMessage; PropertyName = propertyName; } }
source share