views:

929

answers:

1

Hi,

I want to use the error message returned by a RuleViolation as the validationMessage of the Html.ValidationMessage(modelName, validationMessage).

Simple Example: Person.cs

public partial class Person
    {
        public bool IsValid
        {
            get { return (GetRuleViolations().Count() == 0); }
        }

        public IEnumerable<RuleViolation> GetRuleViolations()
        {
            if (String.IsNullOrEmpty(Name))
                yield return new RuleViolation("Name required", "Name");

            yield break;
        }
}

adding errors to modelstate

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

asp page /createPerson/

<%=Html.TextBox("Name",Model.Name)%>
<%=Html.ValidationMessage("Name", "Name required")%>

What I want to do is use the RuleViolation message instead of "Name required" above. Is this possible?

solution is (from Alexander Prokofyev ) use ValidationMessage with a single paramter

<%=Html.ValidationMessage("Name")%>

this is a very simple example, some of my business rules can throw different RuleViolations on an the input depending on the value.

Many thanks. Simon

+3  A: 

You should use ValidationMessage() helpers with only one parameter like

<%= Html.ValidationMessage("Name") %>

and call code

foreach (var ruleViolation in GetRuleViolations())
    ModelState.AddModelError(ruleViolation.PropertyName, 
        ruleViolation.ErrorMessage);

in controller before returning a view (I suppose you have taken RuleViolation class definition from NerdDinner source).

Alexander Prokofyev
Many Thanks Alexander, DOH! moment for me I should have seen that
longhairedsi