How does NerdDinner AddModelErrors work?

I am looking at the free NerDinner tutorial http://nerddinnerbook.s3.amazonaws.com/Intro.htm

I need somewhere in step 5 where it says to make a code cleaner, we can create an extension method. I am looking at the completed code and it has this to use the extension method:

catch { ModelState.AddModelErrors(dinner.GetRuleViolations()); return View(new DinnerFormViewModel(dinner)); } 

And then it's like defining an extension method.

 namespace NerdDinner.Helpers { public static class ModelStateHelpers { public static void AddModelErrors(this ModelStateDictionary modelState, IEnumerable<RuleViolation> errors) { foreach (RuleViolation issue in errors) { modelState.AddModelError(issue.PropertyName, issue.ErrorMessage); } } } } 

I try to keep track of what the tutorial says, combined with what the code contains, but to get the expected error that there is no AddModelErrors method that takes only 1 argument.

I am clearly missing something very important here. What is it?

+4
source share
2 answers

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; } } 
+11
source

If you get the same error message as this poster:

"'System.Web.Mvc.ModelStateDictionary' does not contain a definition for 'AddModelErrors', and the extension method 'AddModelErrors' cannot be found that takes the first argument of the type 'System.Web.Mvc.ModelStateDictionary' (you do not have a using directive or a link to assembly?) "

You may have this problem:

http://p2p.wrox.com/book-professional-asp-net-mvc-1-0-isbn-978-0-470-38461-9/74321-addmodalerrors-allcountries-page-87-view-data- dictionary.html # post248356

+3
source

All Articles