Where do I add this "ControllerHelpers" class?

71 Views Asked by At

In a pretty old .NET tutorial, "Nerd Dinner", it talks about using a Helper Class for Rule Violations. Everything seems straight forward except I'm not sure where to put this class so I can reference it. I am pretty new at MVC.

All of this below was taken from Nerd Dinner Tutorial:

Using a AddRuleViolations Helper Method

Our initial HTTP-POST Edit implementation used a foreach statement within its catch block to loop over the Dinner object's Rule Violations and add them to the controller's ModelState collection:

catch {
    foreach (var issue in dinner.GetRuleViolations()) {
        ModelState.AddModelError(issue.PropertyName, issue.ErrorMessage);
    }

    return View(dinner);
}

We can make this code a little cleaner by adding a "ControllerHelpers" class to the NerdDinner project, and implement an "AddRuleViolations" extension method within it that adds a helper method to the ASP.NET MVC ModelStateDictionary class. This extension method can encapsulate the logic necessary to populate the ModelStateDictionary with a list of RuleViolation errors:

public static class ControllerHelpers {

public static void AddRuleViolations(this ModelStateDictionary modelState, IEnumerable errors) {

   foreach (RuleViolation issue in errors) {
       modelState.AddModelError(issue.PropertyName, issue.ErrorMessage);
   }

} }

0

There are 0 best solutions below